Java program does not execute in Android - 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.

Related

accessing intent views from activity class to java class

I have one java class and one Activity class.
In my java class, it consists of business logic. I want to access the Textviews from activity class to my java class.
If I create an object to activity class. I got all views in activity class as NULL and getting null pointer Exception.
This is my java class here I have created object for activity class and here I am getting NULLpointerException for tdoor.setText() method.
public class Subscribe {
viewtiles vtiles=new viewtiles();
public void sendMessageforstatus(String status)
{
if(status.contains("Door is open"))
{
vtiles.tdoor.setText("OPEN");
}
else if(status.equalsIgnoreCase("Door is close"))
{
vtiles.tdoor.setText("CLOSE");
}
This is my activity layout class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tilesview);
tdoor = (TextView) findViewById(R.id.door2);
}
XML
<RelativeLayout xmlns:android="schemas.android.com/apk/res/android";
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light" >
<TextView android:layout_width="79dp"
android:layout_height="wrap_content"
android:text="Door"
android:layout_marginTop="10dp"
android:layout_marginLeft="52dp"
android:id="#+id/door1"
android:textColor="#android:color/black"
android:textSize="20dp" />
</RelativeLayout>
Can u plzzz help me for this problem...
You can pass TextView object into your Java class,
public void sendMessageforstatus(String status, TextView txt)
{
// example
txt.setText("OPEN");
}

Get Search results from Google in android app

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

AutoCompleteTextView 1. add buttons, 2. create contact adapter, 3. spaces in AutoCompleteTextView

i am trying to make a Compose New Message screen like the Messaging app built-in in Android 4.1
i noticed that when a person selects a contact, there is a Button sort of thing in the AutoCompleteTextView inserted. HOW is that possible? Please help, as I do not even have any idea to give a starting code for it.
P.S. : I would LOVE to implement something like in the "Tags" entry in StackOverflow when creating a new post. I.E. the words (matched contacts) being replaced by buttons, with a little X on the right edge to remove them! :-)
how do you create the adapter which loads so fast? one idea would be to cache a List of all contacts (names, phone no.s, phone no. types). any other ideas ?
(like, if we could query the content provider with an initial search string of say 2 characters, which would reduce the no. of autocomplete results tremenduously, thus reducing the time taken to load the adapter. but of course, this would require to set the adapter for the autocompletetextview as each character is typed. My doubt is that, can the ContactsContract be queried for search results starting with a few given letters, rather than just scanning the entire database from the starting using a Cursor?)
the autocompletetextview does not recognize spaces, and just gives no results.
i have already read this but could not implement it, does anyone have any working code for this?
You free to look at source code of built-in messaging app at Android GitHub. All you need is patience to read and understand code. And i remind you that not all of code are in public SDK so careful in usage.
1, The MultiAutoComplete with Contact tag RecipientEditTextView. And RecipientsEditor is class extended RecipientEditTextView they use it in app
Update : Here is layout of Compose screen. Line 37 is the autocompletetextview you want. And below is its layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<com.android.mms.ui.RecipientsEditor
android:id="#+id/recipients_editor"
android:hint="#string/to_hint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textFilter"
android:layout_weight="1"
android:textColor="#000000"
/>
<ImageButton android:id="#+id/recipients_picker"
android:src="#drawable/ic_launcher_contacts"
android:layout_marginLeft="5dip"
android:layout_width="50dip"
android:layout_height="fill_parent"
android:layout_weight="0"
android:visibility="gone"
/>
I built TokenAutoComplete to solve this issue as there did not appear to be a simple way to do this. Here's a basic example solving points 1 and 3:
public class ContactsCompletionView extends TokenCompleteTextView {
public ContactsCompletionView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected View getViewForObject(Object object) {
Person p = (Person)object;
LayoutInflater l = (LayoutInflater)getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
LinearLayout view = (LinearLayout)l.inflate(R.layout.contact_token, (ViewGroup)ContactsCompletionView.this.getParent(), false);
((TextView)view.findViewById(R.id.name)).setText(p.getName());
return view;
}
#Override
protected Object defaultObject(String completionText) {
//Stupid simple example of guessing if we have an email or not
int index = completionText.indexOf('#');
if (index == -1) {
return new Person(completionText, completionText.replace(" ", "") + "#example.com");
} else {
return new Person(completionText.substring(0, index), completionText);
}
}
}
Layout code for contact_token (you'll need to find your own x drawable)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="#drawable/token_background">
<TextView android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:textSize="14sp"
android:text="Test Me"
android:padding="2dp" />
<ImageView
android:layout_height="10dp"
android:layout_width="10dp"
android:src="#drawable/x"
android:layout_gravity="center_vertical"
android:layout_marginLeft="3dp"
android:layout_marginRight="5dp" />
</LinearLayout>
Token backgound drawable
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#ffafafaf" />
<corners
android:topLeftRadius="5dp"
android:bottomLeftRadius="5dp"
android:topRightRadius="5dp"
android:bottomRightRadius="5dp" />
</shape>
Person object code
public class Person implements Serializable {
private String name;
private String email;
public Person(String n, String e) { name = n; email = e; }
public String getName() { return name; }
public String getEmail() { return email; }
#Override
public String toString() { return name; }
}
Sample activity
public class TokenActivity extends Activity {
ContactsCompletionView completionView;
Person[] people;
ArrayAdapter<Person> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
people = new Person[]{
new Person("Marshall Weir", "marshall#example.com"),
new Person("Margaret Smith", "margaret#example.com"),
new Person("Max Jordan", "max#example.com"),
new Person("Meg Peterson", "meg#example.com"),
new Person("Amanda Johnson", "amanda#example.com"),
new Person("Terry Anderson", "terry#example.com")
};
adapter = new ArrayAdapter<Person>(this, android.R.layout.simple_list_item_1, people);
completionView = (ContactsCompletionView)findViewById(R.id.searchView);
completionView.setAdapter(adapter);
completionView.setTokenClickStyle(TokenCompleteTextView.TokenClickStyle.Delete);
}
}
Layout code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.tokenautocomplete.ContactsCompletionView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Here's what it looks like:

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.

Custom view updating content of another view

I have the following situation:
in the main file I do
setContentView(R.layout.main);
which looks as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/layout"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/result"
android:text="Gesamtstrecke: 0.0"
/>
<test.gustav.Spielfeld
android:id="#+id/spielfeld"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</test.gustav.Spielfeld>
</LinearLayout>
the View "test.gustav.Spielfeld" refers to a class "Spielfeld" extending "View".
I now need a method that updates the content of the TextView with id "result" if a something happens in the onTouchEvent(..)-method in the Spielfeld-View.
How to do this? I've tried making a public TextView in the Main-Class but the Spielfeld class won't accept Main.this.myTextView.
I would recommend a callback approach (just like android does for all events):
Create a interface which represents the callback:
public interface OnSpielfeldUpdate {
public void onSpielfeldUpdate(Object myEventData, ...);
}
Provide a setter for the callback in SpielFeld (which will be used to send updates):
public void setOnSpielfeldUpdate(OnSpielfeldUpdate callback) {
this.callback = callback;
}
Set your callback in your activity (or somewhere else):
mySpielfeld.setOnSpielfeldUpdate(new OnSpielfeldUpdate() {
public void onSpielfeldUpdate(Object myEventData, ...) {
// perform update on result view
}
}

Categories

Resources