Android developer newbie unable to launch code in the emulator - java

Background:
I have started Android recently. I want to make an application for Android that fetches data from a server and customizes it , displays it and then use Twitter to tweet the results. I am thinking to use (twitter4j API for this.).
Initially i have a PERL file on server that i need to call from my application's interface. (I have modified code of HelloWorld.java available at (dev.android..). The PERL file which i have stored on the server has the output in form of print "" I would be using the collective print output and decode them in my application.
Now my code is as follows :
package com.example.helloandroid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloWorldAndroidActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv=new TextView(this);
/* tv.setText("Hello, World !! This is my First Android App .. Cheers");
setContentView(tv);*/
try {
InputStream is = new URL("http://myserver.com:1941/cgi-bin/myperl.pl").openStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String str = in.readLine();
in.close();
tv.setText(str);
setContentView("phew");
} catch (MalformedURLException e) {
//FAIL
} catch (IOException e) {
//FAIL
}
}
}
However i am not able to use the code to get the data from the server file as Eclipse emulator shows up but does not displays anything except the "shinny android logo".
Is there any way i can read that file? Also i would like you seniors to suggest me some startup/dummies book fro Android development.

How long do you want for the emulator to boot up? It can take upwards of two minutes to boot up. It's kind of slow in that respect. Try giving it a little time to actually get to the home screen. Also, is your logcat saying anything interesting?
Also, you're doing a network operation on the main UI thread. NEVER do this. You need to move your network operations on to a different thread. For more details, read Painless Threading.

Related

How to make app refresh for new data everytime app is launch?

I am having hard time understanding, how Android app fetches data or refresh data everytime I launch app.
I have data it is update every minute meaning it is changed, but I don't see it update everytime I launch the app, only randomly it updates the data.
I tired, still doesn't work.
OnResume();
Here is my code.
package com.zv.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ZipActivity extends Activity {
TextView textMsg, textPrompt;
final String textSource = "https://docs.google.com/spreadsheet/pub?key=0AqSBI1OogE84dDJyN0tyNHJENkNyYUgyczVLX0RMY3c&single=true&gid=0&range=a2%3Aa26&output=txt";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textPrompt = (TextView)findViewById(R.id.textprompt);
textMsg = (TextView)findViewById(R.id.textmsg);
textPrompt.setText("Wait...");
URL CPE;
try {
CPE = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(CPE.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer + "\n"; ;
}
bufferReader.close();
textMsg.setText(stringText);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
textPrompt.setText("Finished!");
}
}
You can override the Application class in your application. Define this in your manifest file. Every time your app starts -- no matter how it starts, user click, broadcast intent, service -- your Application class will get an on create.
I think you need to understand the life cycle of an application. Applications on android do not die because you close them. If you want it to update every time it is foregrounded you will have to override the onstart() method in your activities.
The Activity is the building block (better, it was, since now the Fragment API represent the base component) of an Android application. It has so-called lifecycle events which you can hook into. You named:
onCreate(), called by the framework when the Activity is first created. Possibly, this activity object can stay forever, even when other apps take the foreground and after two weeks the user touch you app's icon in the launcher: it may still be the very same Activity object. In reality, Activites are not so long lived, however you get the idea
onResume(), called after onPause(), which in turn is called when the Activity loses the foreground (Note that this has nothing to do with the activity's content visibility). Because onResume() is always called after onPause(), you are guaranteed that it will be called every time the user were doing something else and then switches to your activity, which seems just your use-case.
Note the difference: the user installs your app, touches the icon in the launcher, this fires an intent, the system detects that there's no activity around and creates a new instance. Then calls onResume() and finally takes the activity to the foreground. Next, your receive a SMS notification, you switch to the messanger, then come back to your old activity and onResume() gets called again (but not onCreate).
So if you want to use a lifecycle hook to refresh the Activity's content, onResume() is what you are looking for. However note that once the URL content is read, the content may change and the client won't be notified if the activity still is in the foreground. So you may want to use some sort of server events (push) like C2DM (or websocket, or a plain socket, or whatever you are comfortable with).
Everytime you start your activity the onCreate method is executed, this means that all the code inside that method will be executed again. If the content that you are fetching is not update is probably because is not updated from the source. But then again the refresh will only happen when you start your activity.
you can check this answer it might help you:
https://stackoverflow.com/a/11456974/1552551

How to use a button to within a app to display the phone's contact list

Hello everyone I am completely new to programing no experience at all so please treat me as a 2 year old when you respond. I have alot of time on my hands as I sit in an office with nothing to do so I figure I should do something productive, and since I have a android tablet I figure I'll try to learn how to make apps for it. This is my first attempt and I'm getting an error in the .java portion of the code, I've been reading and reading on various sites and can't seem to get a clear understanding of what I need to do to correct it. PLEASE HELP
Now down to business, in the app I am trying to learn how to display an image its that simple, I'm taking baby steps. So I started a project, read a few tutorials on how to code ImageView and then I got stuck. I have the error that says "The public type TestImages must be defined in its own file" so I ask how to define/create this file? where to put it?
Here is the .java portion of the code where the error lies.
package com.example.myproject;
import com.example.myproject.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
public class TestImages extends Activity {
/**Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
ImageView image = (ImageView) findViewById(R.id.test_image);
}
}
Please help, and if you know of any other resource out there that can help a newbie/dummy like myself who don't know anything about coding and need every detail explained please point me in that direction. I've tried the Android Developers site but the information presented on there are not explained in detail it looks as if they expects everyone who tries to do this have a background in coding and I don't. Oh and please don't discourge encourage, because I'm eager to learn.
use on click listener on the button and then check this
https://github.com/android/platform_packages_apps_contacts

output for System.out.print("Hello") in Android program

I want to see any variable (String var) value in my android program.
You can say for debugging purpose.
When I am printing anything using, say System.out.print("Hello")
Then I am unable find this output any where.
Do anyone have idea where to find this output.
Here is my code-
package com.test1.nus;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.print("Hello");
....
}
By default, the Android system redirects stdout (System.out) output to /dev/null, which means your messages are lost.
Instead, the common pattern to log debug strings in Android is the following
import android.util.Log;
Then at the top of your class YourClass
private static final String TAG = YourClass.class.getSimpleName();
And to log debug strings you need to call
Log.d(TAG, "your debug text here");
which in your case results in
package com.test1.nus;
import android.util.Log;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Hello");
....
}
Finally you can see your debug strings in Eclipse via
Windows > Show view > Other and select LogCat
and if required filter by the tag of YourClass.
However, if you really need to see messages written by System.out.println you need to tell Android to route them to logcat via the following shell commands
$ adb shell stop
$ adb shell setprop log.redirect-stdio true
$ adb shell start
and then you will be able to see your debug messages in Eclipse via LogCat view and the tag stdout.
You can get more details from the official documentation here http://developer.android.com/tools/debugging/debugging-log.html
Your output will be logged to logcat
Assuming you are using eclipse:
Window > Show View ---> Logcat (If this not visible, select other--Android--Logcat)
See this link: http://www.droidnova.com/debugging-in-android-using-eclipse,541.html
It will show some screen shots related to logcat. There you can find out your output message.
Follow this: http://developer.android.com/tools/help/logcat.html
If you want to check your output in the android emulator use Toast messages.
The result with system.out.println("....") will be displayed in logcat.
To check in android emulator/device.just do like this
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show();
I suggest you take a look at the android.util.log class. The Android developer pages has a good introduction for using it. (In fact, I just found this today since I'm learning Android programming myself.)
If you use the AVD s that will give you a more interesting experience than just print in the log. Here they have described all those things perfectly.
You are better off using Logs if it is for debugging purposes.
There are various methods available like Log.v() Log.d() Log.i() Log.w() and Log.e() for verbose, debug, info, warn and error logs respectively.
Then you can check the logcat while debugging the application.
For further reference, go here.

porting screen shot java app on android

i want your help very badly..bcz i am seeking an answer for this from couple of day's but did not find a bit...
my query is i have a screen shot app written in java...i just want to port it on android emulator and run it..i know i have to rewrite some android specific code but can anyone tell me what changes i should make to the screen shot java app to make it run on android platform..
here is my java screen shot app: (i know for this the device should be rooted i am okay for that)
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
class ScreenCapture {
public static void main(String args[]) throws
AWTException, IOException {
// capture the whole screen
BufferedImage screencapture = new Robot().createScreenCapture(
new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );
// Save as JPEG
File file = new File("screencapture.jpg");
ImageIO.write(screencapture, "jpg", file);
// Save as PNG
// File file = new File("screencapture.png");
// ImageIO.write(screencapture, "png", file);
}
}
There aren't just a few changes that you have to made. You have to rewrite the whole app and that wouldn't be so easy since making screenshots in Android isn't this easy as in plain Java.
For example you can't use java.awt.Robot because this lib isn't included in Android.
Afaik you also need root rights on a Android phone to make a screenshot. I would recommend that you google for librarys or apps that are already able to do screenshots and use them.
For example the Android Screenshot Library (ASL) is a good point to start with.

Problem playing audio on android

Amendment: This appears to be a problem with the particular audio file I was using. Other applications on the droid such as the Astro file manager also fail to play it, and if I replace it in the package with an AAC file, it plays it without error. I encoded the problematic audio file to MP3 format from a WAV file, using LAME on ubuntu. It would be good to know the limitations of the android media player. mplayer seems to have no problem playing the file on ubuntu. I suppose I should submit a bug report.
Original question: The following code crashes when I try to play it on my droid. The error message given in the log is "Command PLAYER_INIT completed with an error or info PVMFErrNoResources." Then an IOException is raised on the mp.prepare() line. There is a file res/raw/bell.mp3 in my project directory, which I assume corresponds to R.raw.bell in the code below. I am building with "ant debug". In case it's relevant, when I created the project directory with "android create", I set the target number to 4, corresponding in my system to "android 2.0."
What am I doing wrong, here?
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.util.Log;
public class testapp extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try {
MediaPlayer mp = MediaPlayer.create(this, R.raw.bell);
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
}
You do not need to call prepare() if you use the static create() method to get the MediaPlayer. It does the prepare() step for you. You only need to call prepare() if you either use the regular MediaPlayer constructor or if you are trying to reset the clip back to the beginning to play back from the existing MediaPlayer object.
Here is a sample project for playing back sounds (in my case, an Ogg clip).

Categories

Resources