JVM ? - Tilt, TyTN II, MDA Vario III Themes and Apps

Does anyone know of a JVM for windows mobile 5/6 which supports UDP datagram protocol ?

Seen as though there has been no responses so far.
You could try asking this guy: Menneisyys
Not much he doesn't know about Java.
Thanks
Dave

Do you need J2SE? I think all major JVM's (CrEme, IBM J9, Jeode, MySaifu) support UDP.

No, i'm not after J2SE.
I've trialed the Intent Midlet Manager from Risidoro (this site), the Esmertec JVM and one or two other dodgy implementations I've found around the place ( including IBM MIDP 2.0 Java Emulator V2.3.CAB which does have UDP support but was from a rather obscure dl site).
I am simply looking for a midlet manager for windows mobile which has implemented the UDP protocol. I don't mind paying for it but it does have to be for end-users to download and install.
Any thoughts ?

I think one of the points I may be missing is that the configuration I am looking at is the cldc, not cdc.

Frankly, I don't know - I haven't tested this for myself. Do you have a sample UDP tester MIDlet that I could quickly deploy, or, should I write one? (I'm a seasoned Java / MIDlet programmer but have very little time so I'd prefer the former)

Demo app
This should provide a rough guide to support
Code:
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class TestUDP extends MIDlet {
private final StringBuffer strContent = new StringBuffer();
TextBox textScreen = new TextBox("Location methods TEst", strContent.toString(), 1000, TextField.ANY);
protected void destroyApp(final boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
boolean active = true;
private CommandListener commandListener = new CommandListener() {
public void commandAction(Command cmd, Displayable disp) {
if (cmd.getCommandType() == Command.ITEM) {
active = false;
String str = "";
textScreen.setString(str);
strContent.delete(0, strContent.length());
} else if (cmd.getCommandType() == Command.EXIT) {
active = false;
notifyDestroyed();
} else {
active = true;
new Thread() {
public void run() {
try {
Class.forName("javax.microedition.io.DatagramConnection");
log("Supported");
} catch (ClassNotFoundException e) {
log(e.getMessage());
}
test("datagram://test.com:22");
test("datagram://test.com:22;23");
test("udp://test.com:22");
test("udp://test.com:22;23");
}
private void test(String string) {
try {
Connector.open(string,Connector.READ_WRITE);
log("Success: " + string);
} catch (Throwable e) {
log("Failed: " + string);
}
}
}.start();
}
}
};
protected void startApp() throws MIDletStateChangeException {
Display.getDisplay(this).setCurrent(textScreen);
textScreen.addCommand(new Command("Exit", Command.EXIT, 1));
textScreen.addCommand(new Command("Start", Command.OK, 0));
textScreen.setCommandListener(commandListener);
}
private void log(final String message) {
if (strContent.length() > 200) {
strContent.delete(0, message.length());
}
strContent.append(" \n " + message);
textScreen.setString(strContent.toString());
}
}

Related

Please help with Java homework!!!

Okay here's the thing:
I have an assignment in Java class that's due in 1.5 hours and figured that this would be the best place to ask since you guys are (hopefully) good at this kind of stuff.
Here's the code:
/**
* Exercise 3.
*
* Complete the setBalances method below to set all accounts in an array to the specified value.
*
* The test methods should pass.
*
*/
public class AccountMethods {
public static void main(String[] args) {
Account[] accounts = {new Account(100, "joe"),
new Account(200, "jane"),
new Account(300, "jerry")};
testSetBalances(accounts, 50);
testBalanceNonNegative();
}
public static void setBalances(Account[] accounts, double value) {
double balance = 0;
for (int i = 0; i < accounts.length; i++) {
balance += accounts.getBalance();
}
}
public static boolean testSetBalances(Account[] accounts, double value) {
setBalances(accounts, value);
for (int i = 0; i < accounts.length; i++) {
if (accounts.getBalance() != value) {
System.out.println("testSetBalances fails on element " + i);
return false;
}
}
System.out.println("testSetBalances passes.");
return true;
}
public static boolean testBalanceNonNegative() {
Account a = new Account(100, "jim");
a.setBalance(-100);
if (a.getBalance() < 0) {
System.out.println("testBalanceNonNegtaive fails");
return false;
} else {
System.out.println("testBalanceNonNegative passes.");
return true;
}
}
}
The bold part is what I'm suppose to be working with, but I can't get it to pass in the testSetBalances method. I don't know if I'm explaining this right, but when I'm compiling the code, it's suppose to say:
testSetBalances passes
But instead, it's saying: testSetBalances fails on element 0
Don't worry about the other parts of the code because the assignment for that is done already.

The Wrong Activity Shows Up Android Studio

Can anybody help me. I have developed a quiz app. At the end of the quiz the result activity must show up but the scores activity shows up. The scores activity only shows up when the scores button is selected on the MainActivity.
Quiz.java
Code:
package app.mobiledevicesecurity;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Quiz extends Activity
{
List<Question> questionList;
int score = 0;
int qid = 0;
Question currentQuest;
TextView txtQuestion, scored;
Button button1, button2, button3;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
QuizHelper db = new QuizHelper(this);
questionList = db.getAllQuestions();
currentQuest = questionList.get(qid);
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
scored = (TextView) findViewById(R.id.score);
setQuestionView();
button1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
}
public void getAnswer(String AnswerString)
{
if (currentQuest.getAnswer().equals(AnswerString))
{
score++;
scored.setText("Score : " + score);
}
else
{
Intent intent = new Intent(Quiz.this,
Result.class);
Bundle b = new Bundle();
b.putInt("score", score);
intent.putExtras(b);
startActivity(intent);
finish();
}
if (qid < questionList.size()) {
currentQuest = questionList.get(qid);
setQuestionView();
}
else
{
Intent intent = new Intent(Quiz.this,
Result.class);
Bundle b = new Bundle();
b.putInt("score", score);
intent.putExtras(b);
startActivity(intent);
finish();
}
}
private void setQuestionView()
{
txtQuestion.setText(currentQuest.getQuest());
button1.setText(currentQuest.getOption1());
button2.setText(currentQuest.getOption2());
button3.setText(currentQuest.getOption3());
qid++;
}
}
Result.java
Code:
package app.mobiledevicesecurity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Result extends Activity {
private static Button playbtn;
private static Button menubutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
OnClickPlayButtonListener();
OnClickMenuButtonListener();
TextView textResult = (TextView) findViewById(R.id.textResult);
Bundle b = getIntent().getExtras();
int score = b.getInt("score");
textResult.setText("You scored" + " " + score + " for the quiz.");
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
finish();
}
public void OnClickPlayButtonListener() {
playbtn = (Button) findViewById(R.id.btn);
playbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickMenuButtonListener() {
menubutton = (Button) findViewById(R.id.menubtn);
menubutton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
);
}
}
Scores.java
Code:
package app.mobiledevicesecurity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.content.Intent;
public class Scores extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scores);
TextView txtScore1 = (TextView) findViewById(R.id.txtScore1);
Bundle bun = getIntent().getExtras();
int score = bun.getInt("score");
txtScore1.setText("score:" + " " + score + " for the quiz.");
}
@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_scores, 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);
}
}
You are doing it wrong once you send the intent to start the Result Activity you have this code on your onCreate method:
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
finish();
Which causes the Result activity to launch Scores and close Result
Please move this code out of your onCreate method and only call it when you need to!
Can you maybe help me with this. I am in the process of learning this application development. The score must be passed over to the Scores.java activity
This is what I tried but it do not work:
Result.java:
Code:
package app.mobiledevicesecurity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Result extends Activity {
private static Button playbtn;
private static Button menubutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
OnClickPlayButtonListener();
OnClickMenuButtonListener();
TextView textResult = (TextView) findViewById(R.id.textResult);
Bundle b = getIntent().getExtras();
int score = b.getInt("score");
textResult.setText("You scored" + " " + score + " for the quiz.");
}
public void getScore()
{
Bundle b = getIntent().getExtras();
int score = b.getInt("score");
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
finish();
}
public void OnClickPlayButtonListener() {
playbtn = (Button) findViewById(R.id.btn);
playbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickMenuButtonListener() {
menubutton = (Button) findViewById(R.id.menubtn);
menubutton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
);
}
}
Scores.java:
Code:
package app.mobiledevicesecurity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.content.Intent;
public class Scores extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scores);
Result res = new Result();
res.getScore();
TextView txtScore1 = (TextView) findViewById(R.id.txtScore1);
Bundle bun = getIntent().getExtras();
int score = bun.getInt("score");
txtScore1.setText("Last quiz score:" + " " + score + ".");
}
@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_scores, 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);
}
}
Logcat:
Code:
09-08 20:47:51.143 1050-1050/app.mobiledevicesecurity E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: app.mobiledevicesecurity, PID: 1050
java.lang.RuntimeException: Unable to start activity ComponentInfo{app.mobiledevicesecurity/app.mobiledevicesecurity.Scores}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at app.mobiledevicesecurity.Result.getScore(Result.java:31)
at app.mobiledevicesecurity.Scores.onCreate(Scores.java:18)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
************at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
************at android.app.ActivityThread.access$800(ActivityThread.java:151)
************at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
************at android.os.Handler.dispatchMessage(Handler.java:102)
************at android.os.Looper.loop(Looper.java:135)
************at android.app.ActivityThread.main(ActivityThread.java:5257)
************at java.lang.reflect.Method.invoke(Native Method)
************at java.lang.reflect.Method.invoke(Method.java:372)
************at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
************at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
This is wrong:
Result res = new Result();
res.getScore();
You are instantiating a new Result Activity which of course will have a null bundle because its not the same original Result Activity! What you are doing is the same has storing something on your box object named "box1" and then create a new box named "box2" and hope the object you stored will be on this new box!
If i understood correctly you want to show the result activity on the end of the quiz which you seemed to have working. And now you want to show the scores activity on press of a button on the main activity correct?
For that create a listener for the scores button on your Main Activity and add code to launch the Scores Activity with an intent where you pass the score. And then retrieve the bundle on your onCreate method on your ScoresActivity!
Can you maybe help me. I understand what you say but do not know how to do it.
Here is my main activity:
Code:
package app.mobiledevicesecurity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
DatabaseHelper myDb;
private static Button readbtn;
private static Button quizbtn;
private static Button scoresbtn;
private static Button settingsbtn;
private static Button helpbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
myDb.insertData();
OnClickReadButtonListener();
OnClickQuizButtonListener();
OnClickScoresButtonListener();
OnClickSettingsButtonListener();
OnClickHelpButtonListener();
}
public void OnClickReadButtonListener() {
readbtn = (Button) findViewById(R.id.readbutton);
readbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Read_Category");
startActivity(intent);
}
}
);
}
public void OnClickQuizButtonListener() {
quizbtn = (Button) findViewById(R.id.quizbutton);
quizbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickScoresButtonListener() {
scoresbtn = (Button) findViewById(R.id.scoresbutton);
scoresbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Scores");
startActivity(intent);
}
}
);
}
public void OnClickSettingsButtonListener() {
settingsbtn = (Button) findViewById(R.id.settingsbutton);
settingsbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Settings");
startActivity(intent);
}
}
);
}
public void OnClickHelpButtonListener() {
helpbtn = (Button) findViewById(R.id.helpbutton);
helpbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Help");
startActivity(intent);
}
}
);
}
@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);
}
}
Android Studio Eclipse - 1
I wonder if I 10 of the many many who call to use FDI. In my 20 years I have been on 1: MS Visual Studio, 2: Eclipse 3: STS (spring version of Eclipse), 4: RAD (IBM Websphere version eclipse commercially), 5: and now Netbeans 6: IntelliJ. The last one is my favorite by far far away. When you say many many Suppose you can take a little more to the list?
I let Visual Studio, because I. To Java instead of C ++ I went into eclipse, because that's what everyone else was doing, so I thought it was the only tool. I moved to STS because I look for alternatives, because eclipse was anything but stable, if you use EJB, Spring, Hibernate and one of the usual suspects in the application server where the debugging and publishing is a very regular basis. I had to use RAD, because a customer forced me. RAD6.2 and if the company that I was, I was probably still sued IBM as RAD6.2 is not even worth called a beta version. Since none of the releabed of the Eclipse-based IDE agony I have so hard to avoid, tried, I tried NetBeans. And things clarified. By integrating Maven was better than the eclipse. Honesty I admit liable that I never really know him so well, because professional, everyone was from Eclipse moving to IntelliJ, and I felt nothing but relief, where once swore. And so I joined the hive.
And I'm glad that I did it. IntelliJ is not perfect, but in my humble opinion, approaches. And if you have a problem, send an email to get these people and nine out of ten an answer within an hour. In the worst case within a day. At least in my case, as a paying customer.
I can not comment on Eclipse with the development of Android. I am pleased to talk about Java developers. For me, the Eclipse is a past long forgotten. Never again.
#Eclipse.
The Wrong Activity Shows Up Android Studio OK - we have it, you hate Eclipse. Personally, I find that the argument pointless. I do not like Eclipse, but I have many, many IDEs that were much worse used. Many developers - including myself - to live well with Eclipse for the daily work, either by choice or simply because we have to. Is set correctly Eclipse IDE a solid. Arguing that it fragile, even if the "stable" version of Android Studio still hangs / freezes it seems quite often rather disingenuous.
The other thing, this article makes completely useless is that they are all reasons (mostly true) for the reason why Android Studio is listed size. They forget to mention the various reasons - equally valid - because Android Studio is terrible (in the same way that we speak only bad problems with Eclipse, but none of its strengths).
Personally, I think Android Studio is practically dead, and is never more than a footnote in the history of the development of Android to be. One reason is due to the fact the unit - another is simply the inevitable course of development.
# 1 Android libraries
More than a year has passed since the AS was launched, and Google has not yet developed a sensible approach with Android libraries. Never tried above also brings a relatively simple configuration library? I tried to explain how to install the libraries in Android as for a new developer? There are zero relevant documents on the website and 50% of what it is out of date on the Internet - the remaining 50% is a terrible reading. Re usability of the code is the cornerstone of good development practices, but there are exercises that suggest in all seriousness physically copy code between projects in Android Studio. 1970 called ...
Inability of Google to provide a simple and intuitive code reuse mechanical - especially after (finally) it did work in Eclipse, IMO is the only major flaw Android Studio. At the same time makes it impossible for developers to have a choice (for example, everything is in Eclipse or AS) is just icing on the cake.
Even if - if you can just explain how multiple applications with multiple libraries Androdi (and some libraries use each other) set up, then I would see such a blog post. More than that - I would be very impressed. I tried it myself and it failed - and I have not seen anyone doing it. IMO - when a build tool is only for experts, it is a poor tool of creation. Gradle for Android is just that. Few can the software companies, technology that afford to introduce to understand only 1-2 people at home.
# 2 Google is not interested in having Android SDK to survive
For me, this is the largest study problem Android. It is an IDE for what developed a dying language. Android Studio is already dead.
Why? Since cross-platform (ie, at least Android + IOS) is the only sensible choice if you want to start the development of mobile applications today. Limit yourself to a single platform is just silly - and especially for the Games (which is - I would remind you - 90% of sales in the App Store), there are many, many excellent multi-platform tools like unit and Cocos2dx. None of them have Java or the Android SDK as a development language.
If Google wanted Android Java must be more than a footnote in history, they would have made an effort - any effort - it is Java Android cross-compiled on other platforms. At least one could the Android SDK can create programs Chrome, or even Android applications compiled directly from desktop applications. Both would be relatively simple. They will not, though. Instead dithering about Android and Chrome OS they want to support.
Of course - some argue that Google has already decided, and the choice is Chrome OS. Soon you can applications can run Chrome either in Chrome OS, Android, iOS and Google (has already announced that, based on Apache Cordoba) Personally, I'm not quite sure that Google has not to develop their minds yet, but ultimately developing the Community to make the choice for them, and is not to be Android SDK.
I'm not saying that he die this year or next - but at some point it becomes very clear that Google is not interested in who became the development of native Android (in typical Google approach, it does not surprise me if it even makes it Studio to Android 1.0). And I say this not because I hate Android - I love the strengths of the Android SDK, and I would no more joy love to hear Google ads to make I / O to show that they are going to the Android SDK build. I doubt that will happen when.
Ironically, starting as a developer, leaving Android SDK (Android and Studio), one of the languages ​​that are likely to encounter, JavaScript (the language of choice for Google Chrome OS), which often lead people back in .... Eclipse.

Badly confused with AsyncTask .. someone please help out .. ty

Am creating a form application which allows users to send a message using http POST request..Am getting a android.os.NetworkOnMainThreadException while running my program. I am fairly new to android dev. Can someone help me by rewriting the network related operation in AsyncTask. If someone can rewrite, i can learn how exactly network tasks can be done using Async. Ty
Code:
public class MainActivity extends Activity {
EditText msgTextField;
Button sendButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
//make button object
sendButton = (Button) findViewById(R.id.sendButton);
}
public void send(View v)
{
//get message from message box
String msg = msgTextField.getText().toString();
//check whether the msg empty or not
if(msg.length()>0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("localhost");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("name", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
msgTextField.setText(""); //reset the message text field
Toast.makeText(getBaseContext(),"Successfully Booked!!",Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
}
}
}
any help ??
Hello,
Make a copy of the send(View v) method and name it sendAsync(View v, EditText msgbox).
Like this:
Code:
public Exception sendAsync(View v, EditText msgbox)
{
[B] HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("localhost");[/B]
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("name", msgbox.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
return null;
} catch (ClientProtocolException e) {
return e;
} catch (IOException e) {
return e;
}
}
Next, modify the original send(View v) method like this:
Code:
public void send(View v)
{
//get message from message box
String msg = msgTextField.getText().toString();
//check whether the msg empty or not
if(msg.length()>0) {
MyAsyncTask mAsync = new MyAsyncTask(v, getBaseContext(), msgTextField);
mAsync.execute();
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
}
}
You can add the below code inside your activity class (outside the onCreate method)
Code:
private class MyAsyncTask extends AsyncTask<String, Void, String> {
View v;
Context context;
EditText msgbox;
Exception e = null;
public MyAsyncTask(View v_, Conext context_, EditText msgbox_){
this.v = v_;
this.context = context_;
this.msgbox = msgbox_;
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
this.e = sendAsync(v, msgbox);
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
if(e==null){
//Successful
msgbox.setText(""); //reset the message text field
Toast.makeText(context,"Successfully Booked!!",Toast.LENGTH_SHORT).show();
}
else{
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
@Override
protected void onProgressUpdate(Void... values) {
//Called on Main UI Thread
}
}
However, HttpClient is deprecated for API Level 22 and above, so you should use HttpURLConnection instead. This may help you out for using HttpURLConnection via POST or GET Method.
Now, the doInBackground method, runs in a background thread, automatically created for you, and so we send the data from there, for not crashing the UI (User Interface) of the Android App. If you want, however, to access some UI components, you can do it in the onPostExecute (it is executed after the doInBackground completes) or in the onPreExecute (it is executed before the doInBackground begins). To learn more about the AsyncTask class, check here.
AsyncTask can be used and for other purposes other than sending data over the Internet. In general, you create a class extending the AsyncTask, pass any parameters that you are going to use in the background thread (but not UI components like EditText, you can pass them though, but use them in the onPreExecute or onPostExecute methods, and not in the doInBackground method), and do the stuff you want to run in the background thread inside the doInBackground method. That way, heavy(time consuming) computations or tasks like sending data over the Internet does not make your UI to crash, meaning that the user can press any buttons (for example) without lag or without waiting for the background task to finish.
i tried .. it didnt work for me .. can u give the full code for this please ?
package com.example.formpost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText msgTextField;
Button sendButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
//make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
//make button object
sendButton = (Button) findViewById(R.id.sendButton);
}
public void send(View v)
{
//get message from message box
String msg = msgTextField.getText().toString();
//check whether the msg empty or not
if(msg.length()>0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("serverside-script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("message", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
msgTextField.setText(""); //reset the message text field
Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
}
}
}
Click to expand...
Click to collapse
Thanks bro
I just made a correction on the sendAsync method. It should be as follows (I have also updated my initial post):
Code:
public Exception sendAsync(View v, EditText msgbox)
{
[B] HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("localhost");[/B]
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("name", msgbox.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
return null;
} catch (ClientProtocolException e) {
return e;
} catch (IOException e) {
return e;
}
}
(Replace "localhost" with the actual URL that will handle the POST HTTP request). Also if you are on a local network (LAN), and trying to access the localhost of your PC that is connected to the same LAN as your Android smartphone, then, you should find the local internal IP of your computer, e.g. 192.168.1.1 (you can find that from the command prompt by typing: ipconfig). It's the IPv4 Address on your ethernet or wifi (whatever connection your PC has to the router).
Also make sure that your firewall does not block the connection.
Hope it works. What is the error that you get?
try using volley library for http requests .just a few bunch of line. no need of using async tasks.it will handle it automatically
Sent from my Nexus 4 using Tapatalk
jaison thomas said:
try using volley library for http requests .just a few bunch of line. no need of using async tasks.it will handle it automatically
Sent from my Nexus 4 using Tapatalk
Click to expand...
Click to collapse
Since am new to this whole thing, i wanted to learn with this. It was the only tutorial project i could see. Its been depreciated, but still for learning purpose i wanted to execute it. Still no success.

Black screen and app shutdown when trying to go back to the previous activity/view

When i run my script below everything works fine. When i want to go back to the previous activity i get a black screen on the emulator and then the app shuts down, i also get a black screen when i exit the application and try to resume it.
The script:
Code:
package com.example.bono.as3;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
import java.io.InputStream;
public class Main extends Activity {
DrawView drawView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
setContentView(drawView);
}
@Override public void onResume(){
super.onResume();
drawView.resume();
}
@Override public void onPause(){
super.onPause();
drawView.pause();
}
public class DrawView extends SurfaceView implements Runnable{
Thread gameloop = new Thread();
SurfaceHolder surface;
volatile boolean running = false;
AssetManager assets = null;
BitmapFactory.Options options = null;
Bitmap incect[];
int frame = 0;
public DrawView(Context context){
super(context);
surface = getHolder();
assets = context.getAssets();
options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
incect = new Bitmap[2];
try {
for (int n = 0; n < incect.length; n++){
String filename = "incect"+Integer.toString(n+1)+".png";
InputStream istream = assets.open(filename);
incect[n] = BitmapFactory.decodeStream(istream,null,options);
istream.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
public void resume(){
running = true;
gameloop = new Thread(this);
gameloop.start();
}
public void pause(){
running = false;
while (true){
try {
gameloop.join();
}
catch (InterruptedException e){}
}
}
@Override public void run (){
while (running){
if (!surface.getSurface().isValid())
continue;
Canvas canvas = surface.lockCanvas();
canvas.drawColor(Color.rgb(85, 107, 47));
canvas.drawBitmap(incect[frame], 0, 0, null);
surface.unlockCanvasAndPost(canvas);
frame++;
if (frame > 1) frame = 0;
try {
Thread.sleep(500);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
I dont get any error message in the log, what i do get is about 13 messages saying "suspending all threads took: X ms" so it has something to the with my gameloop Thread i think. Unfortunately i dont see what the problem is in my code... Can anyone help me with this?

Google Maps API v2 tutorials wanted.

Hi everyone,
I'm working on my first app (still a noob) with Google Maps API v2 in Android Studio and followed a couple of tutorials to get the user's current position and draw a path between two points (not working right now). I am using Retrofit to parse JSON. Now I have a current position and when the user taps the screen, a green marker appears and when the user taps again a red marker appears. Clicking on my driving button to get the route between red and green does nothing.
I would like the current position of the user also to be the starting point (so no extra markers). A user has to be able to enter an address and a new marker has to be set at that address. A route should be drawn between the current position of the user and the new address (showing distance and time) Like Runkeeper, I would like that - when the user moves - the marker at the current position moves with him.
I just can't find any good up to date tutorials which I can use to create this? Is someone able to help me or could someone look at my code? Or know any good tutorials?
Code:
package com.lemonkicks.trackmycab.trackmycab;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.lemonkicks.trackmycab.trackmycab.POJO.Example;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.ArrayList;
import java.util.List;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
LatLng origin;
LatLng dest;
ArrayList<LatLng> MarkerPoints;
TextView ShowDistanceDuration;
Polyline line;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
ShowDistanceDuration = (TextView) findViewById(R.id.show_distance_time);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Initializing
MarkerPoints = new ArrayList<>();
//show error dialog if Google Play Services not available
if (!isGooglePlayServicesAvailable()) {
Log.d("onCreate", "Google Play Services not available. Ending Test case.");
finish();
} else {
Log.d("onCreate", "Google Play Services available. Continuing.");
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Setting onclick event listener for the map
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
// clearing map and generating new marker points if user clicks on map more than two times
if (MarkerPoints.size() > 1) {
mMap.clear();
MarkerPoints.clear();
MarkerPoints = new ArrayList<>();
ShowDistanceDuration.setText("");
}
// Adding new item to the ArrayList
MarkerPoints.add(point);
Log.i("onMapClick", "Map clicked, number of points is now " + MarkerPoints.size());
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if (MarkerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (MarkerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
mMap.addMarker(options);
// Checks, whether start and end locations are captured
if (MarkerPoints.size() >= 2) {
origin = MarkerPoints.get(0);
dest = MarkerPoints.get(1);
Log.i("onMapClick", "origin and dest now set.");
} else {
Log.i("onMapClick", "origin and dest not set as number of marker points is " + MarkerPoints.size());
}
}
});
Button btnDriving = (Button) findViewById(R.id.btnDriving);
btnDriving.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
build_retrofit_and_get_response("driving");
}
});
Button btnWalk = (Button) findViewById(R.id.btnWalk);
btnWalk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
build_retrofit_and_get_response("walking");
}
});
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private void build_retrofit_and_get_response(String type) {
String url = "https://maps.googleapis.com/maps/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitMaps service = retrofit.create(RetrofitMaps.class);
Call<Example> call = service.getDistanceDuration("metric", origin.latitude + "," + origin.longitude,dest.latitude + "," + dest.longitude, type);
call.enqueue(new Callback<Example>() {
@Override
public void onResponse(Response<Example> response, Retrofit retrofit) {
try {
//Remove previous line from map
if (line != null) {
line.remove();
}
// This loop will go through all the results and add marker on each location.
for (int i = 0; i < response.body().getRoutes().size(); i++) {
String distance = response.body().getRoutes().get(i).getLegs().get(i).getDistance().getText();
String time = response.body().getRoutes().get(i).getLegs().get(i).getDuration().getText();
ShowDistanceDuration.setText("Distance:" + distance + ", Duration:" + time);
String encodedString = response.body().getRoutes().get(0).getOverviewPolyline().getPoints();
List<LatLng> list = decodePoly(encodedString);
line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(20)
.color(Color.RED)
.geodesic(true)
);
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng( (((double) lat / 1E5)),
(((double) lng / 1E5) ));
poly.add(p);
}
return poly;
}
// Checking if Google Play Services Available or not
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
}

Categories

Resources