convert string array to int - java

I am trying to convert a array with text and numbers to an int.
the array separated:
separated[0] some text
separated[1] 1
separated[2] some more text
What I want is that the [1] ends up being a int.
I tried:
int logSetting = Integer.parseInt(String.valueOf(separated));
and
int logSetting = Integer.parseInt(String.valueOf(separated[1]));
Both made the app crash
09-16 09:57:30.865: E/AndroidRuntime(27938): FATAL EXCEPTION: main
09-16 09:57:30.865: E/AndroidRuntime(27938): Process: my.project, PID: 27938
09-16 09:57:30.865: E/AndroidRuntime(27938): java.lang.NumberFormatException: Invalid int:
"[Ljava.lang.String;#42b273f0"
09-16 09:57:30.865: E/AndroidRuntime(27938): at java.lang.Integer.invalidInt(Integer.java:137)
09-16 09:57:30.865: E/AndroidRuntime(27938): at java.lang.Integer.parse(Integer.java:374)
09-16 09:57:30.865: E/AndroidRuntime(27938): at java.lang.Integer.parseInt(Integer.java:365)
09-16 09:57:30.865: E/AndroidRuntime(27938): at java.lang.Integer.parseInt(Integer.java:331)
09-16 09:57:30.865: E/AndroidRuntime(27938): at my.project.MainActivity.fileReader(MainActivity.java:928)
09-16 09:57:30.865: E/AndroidRuntime(27938): at my.project.MainActivity.logCat(MainActivity.java:944)
09-16 09:57:30.865: E/AndroidRuntime(27938): at my.project.MainActivity$1.run(MainActivity.java:854)
09-16 09:57:30.865: E/AndroidRuntime(27938): at android.os.Handler.handleCallback(Handler.java:733)
09-16 09:57:30.865: E/AndroidRuntime(27938): at android.os.Handler.dispatchMessage(Handler.java:95)
09-16 09:57:30.865: E/AndroidRuntime(27938): at android.os.Looper.loop(Looper.java:157)
09-16 09:57:30.865: E/AndroidRuntime(27938): at android.app.ActivityThread.main(ActivityThread.java:5356)
09-16 09:57:30.865: E/AndroidRuntime(27938): at java.lang.reflect.Method.invokeNative(Native Method)
09-16 09:57:30.865: E/AndroidRuntime(27938): at java.lang.reflect.Method.invoke(Method.java:515)
09-16 09:57:30.865: E/AndroidRuntime(27938): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
09-16 09:57:30.865: E/AndroidRuntime(27938): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
09-16 09:57:30.865: E/AndroidRuntime(27938): at dalvik.system.NativeStart.main(Native Method)

You can do something like this
String[] separated=new String[]{"some text ","1","some more text"};
int logSetting = 0;
for(String i:separated){
try {
logSetting = Integer.parseInt(i);
}catch (NumberFormatException e){
System.out.println("NumberFormatException \""+i+"\" is not a number");
}
}
System.out.println(logSetting);
Out put:
NumberFormatException "some text " is not a number
NumberFormatException "some more text" is not a number
1

You're almost there, int logSetting = Integer.parseInt(String.valueOf(separated[1])); should just be int logSetting = Integer.parseInt(separated[1]);. If this doesn't work its probably something else crashing your code. What error do you get?

Based on your exception which is NumberFormatException, when you try to convert a String to a numeric value, like an int, float, double, long, etc which does not have right format
For example:
public class ConvertStringToNumber
{
public static void main(String[] args)
{
try
{
String s = "FOOBAR";
int i = Integer.parseInt(s); <--this line of code will never be reached
System.out.println("int value = " + i);
}
catch (NumberFormatException nfe)
{
nfe.printStackTrace();
}
}
Source for the Code
Read more and Another Source

Related

Edittext to ratingbar in Android

This is my first question here so I would ask you not to be tough on me if I violate some rules, etc.
I am developing an Android project with a ratingbar. I try to get a number from edittext and pass its value to the ratingbar. I get a nullpointerexception and can't get past this, any help will be appreciated.
Here is the portion of relevant code:
public void bindView(View movieView, Context context, Cursor cursor)
{
final Movie movie = new Movie(cursor);
Holder holder = (Holder)movieView.getTag();
holder.setMovie(movie);
TextView movieTitleText = (TextView)movieView.findViewById(R.id.movieTitleText);
TextView movieDescriptionText = (TextView)movieView.findViewById(R.id.movieDescriptionText);
RatingBar rb = (RatingBar)movieView.findViewById(R.id.movieRatingBar);
rb.setNumStars(5);
rb.setMax(5);
rb.setRating(2.4F);
rb.setEnabled(false);
rb.setFocusable(false);
float numRate = 0;
numRate = Float.parseFloat(movie.getRating().toString());
rb.setRating(numRate);
movieTitleText.setText(movie.getTitle());
movieDescriptionText.setText(movie.getDescription());
movieView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Short click", Toast.LENGTH_LONG).show();
Intent editIntent = new Intent(MoviesActivity.this, EditMovieActivity.class);
editIntent.putExtra("isNew",false);
editIntent.putExtra("title", movie.getTitle());
editIntent.putExtra("description", movie.getDescription());
editIntent.putExtra("year", movie.getYear());
editIntent.putExtra("rating", movie.getRating());
editIntent.putExtra("rottenId", movie.getRottenId());
editIntent.putExtra("smallImage", movie.getSmallImage());
editIntent.putExtra("largeImage", movie.getLargeImage());
startActivityForResult(editIntent,EDIT_MOVIE_REQUEST_CODE);
}
});
movieView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
Toast.makeText(getApplicationContext(), "Long click", Toast.LENGTH_LONG).show();
AlertDialog.Builder editBuilder = new AlertDialog.Builder(MoviesActivity.this);
editBuilder.setTitle("Edit or Clear Movie").setMessage("Please choose either to clear or to edit the movie");
editBuilder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent editIntent = new Intent(MoviesActivity.this, EditMovieActivity.class);
editIntent.putExtra("isNew",false);
editIntent.putExtra("title", movie.getTitle());
editIntent.putExtra("description", movie.getDescription());
editIntent.putExtra("year", movie.getYear());
editIntent.putExtra("rating", movie.getRating());
editIntent.putExtra("rottenId", movie.getRottenId());
editIntent.putExtra("smallImage", movie.getSmallImage());
editIntent.putExtra("largeImage", movie.getLargeImage());
startActivityForResult(editIntent,EDIT_MOVIE_REQUEST_CODE);
}
});
editBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
return;
}
});
Builder setNeutralButton = editBuilder.setNeutralButton("Clear movie", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.deleteMovie(movie.getId());
moviesCursor = handler.getAllMoviesCursor();
adapter.swapCursor(moviesCursor);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Movie deleted", Toast.LENGTH_LONG).show();
}
});
editBuilder.show();
return true;
}
});
}
and here is the stack trace:
09-16 03:41:28.912: E/AndroidRuntime(1248): FATAL EXCEPTION: main
09-16 03:41:28.912: E/AndroidRuntime(1248): java.lang.NullPointerException
09-16 03:41:28.912: E/AndroidRuntime(1248): at com.rotten.tomatoes.MoviesActivity$MyCursorAdapter.bindView(MoviesActivity.java:209)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.support.v4.widget.CursorAdapter.getView(CursorAdapter.java:256)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.AbsListView.obtainView(AbsListView.java:2033)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.ListView.makeAndAddView(ListView.java:1772)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.ListView.fillDown(ListView.java:672)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.ListView.fillFromTop(ListView.java:732)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.ListView.layoutChildren(ListView.java:1625)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.AbsListView.onLayout(AbsListView.java:1863)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.view.View.layout(View.java:11278)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.view.ViewGroup.layout(ViewGroup.java:4224)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1628)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1486)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.LinearLayout.onLayout(LinearLayout.java:1399)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.view.View.layout(View.java:11278)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.view.ViewGroup.layout(ViewGroup.java:4224)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.FrameLayout.onLayout(FrameLayout.java:431)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.view.View.layout(View.java:11278)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.view.ViewGroup.layout(ViewGroup.java:4224)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1628)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1486)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.LinearLayout.onLayout(LinearLayout.java:1399)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.view.View.layout(View.java:11278)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.view.ViewGroup.layout(ViewGroup.java:4224)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.widget.FrameLayout.onLayout(FrameLayout.java:431)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.view.View.layout(View.java:11278)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.view.ViewGroup.layout(ViewGroup.java:4224)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1489)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.os.Handler.dispatchMessage(Handler.java:99)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.os.Looper.loop(Looper.java:137)
09-16 03:41:28.912: E/AndroidRuntime(1248): at android.app.ActivityThread.main(ActivityThread.java:4424)
09-16 03:41:28.912: E/AndroidRuntime(1248): at java.lang.reflect.Method.invokeNative(Native Method)
09-16 03:41:28.912: E/AndroidRuntime(1248): at java.lang.reflect.Method.invoke(Method.java:511)
09-16 03:41:28.912: E/AndroidRuntime(1248): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-16 03:41:28.912: E/AndroidRuntime(1248): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-16 03:41:28.912: E/AndroidRuntime(1248): at dalvik.system.NativeStart.main(Native Method)
Thanks a lot!

Android: Passing Int with Intent crashing app [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Hi hoping someone can help me with a error i'm getting when running my code. What want is when the user gets game over the score from the main class is taken to the gameover class to display the final score. without the intent the game over screen loads fine but when I add the intent upon gameover running the game the app crashes Here is my code where score is the int:
main class intent:
Intent myIntent = new Intent(MainActivity.this,gameover.class);
myIntent.putExtra("number", score);
MainActivity.this.startActivity(myIntent);
gameover class:
EndScore = (TextView) findViewById(R.id.show);
int numScore;
numScore = getIntent().getExtras().getInt("number");
String s = String.valueOf( numScore );
EndScore.setText(s);
I have been looking around the forums but can't see what I am doing wrong.
Log is as follows:
12-28 02:36:37.760: I/Adreno200-EGLSUB(17096): <ConfigWindowMatch:2081>: Format RGBA_8888.
12-28 02:36:37.770: D/memalloc(17096): /dev/pmem: Mapped buffer base:0x5189a000 size:4866048 offset:4251648 fd:68
12-28 02:36:37.860: D/memalloc(17096): /dev/pmem: Mapped buffer base:0x51e6e000 size:2949120 offset:2334720 fd:71
12-28 02:36:38.870: W/dalvikvm(17096): threadid=1: thread exiting with uncaught exception (group=0x40b0a9f0)
12-28 02:36:38.880: E/AndroidRuntime(17096): FATAL EXCEPTION: main
12-28 02:36:38.880: E/AndroidRuntime(17096): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.phil3992.colourguess/com.phil3992.colourguess.gameover}: java.lang.NullPointerException
12-28 02:36:38.880: E/AndroidRuntime(17096): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
12-28 02:36:38.880: E/AndroidRuntime(17096): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
12-28 02:36:38.880: E/AndroidRuntime(17096): at android.app.ActivityThread.access$600(ActivityThread.java:123)
12-28 02:36:38.880: E/AndroidRuntime(17096): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
12-28 02:36:38.880: E/AndroidRuntime(17096): at android.os.Handler.dispatchMessage(Handler.java:99)
12-28 02:36:38.880: E/AndroidRuntime(17096): at android.os.Looper.loop(Looper.java:137)
12-28 02:36:38.880: E/AndroidRuntime(17096): at android.app.ActivityThread.main(ActivityThread.java:4424)
12-28 02:36:38.880: E/AndroidRuntime(17096): at java.lang.reflect.Method.invokeNative(Native Method)
12-28 02:36:38.880: E/AndroidRuntime(17096): at java.lang.reflect.Method.invoke(Method.java:511)
12-28 02:36:38.880: E/AndroidRuntime(17096): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
12-28 02:36:38.880: E/AndroidRuntime(17096): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
12-28 02:36:38.880: E/AndroidRuntime(17096): at dalvik.system.NativeStart.main(Native Method)
12-28 02:36:38.880: E/AndroidRuntime(17096): Caused by: java.lang.NullPointerException
12-28 02:36:38.880: E/AndroidRuntime(17096): at com.phil3992.colourguess.gameover.onCreate(gameover.java:22)
12-28 02:36:38.880: E/AndroidRuntime(17096): at android.app.Activity.performCreate(Activity.java:4470)
12-28 02:36:38.880: E/AndroidRuntime(17096): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
12-28 02:36:38.880: E/AndroidRuntime(17096): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
12-28 02:36:38.880: E/AndroidRuntime(17096): ... 11 more
The int is increment when the user scores a point then on game over it should send and be shown in the textview
Update whole gameover class:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class gameover extends Activity {
Button re_run;
TextView EndScore;
#Override
public void onCreate(Bundle savedInstanceState) {
re_run = (Button) findViewById(R.id.retry);
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
EndScore = (TextView) findViewById(R.id.show);
int numScore;
numScore = getIntent().getExtras().getInt("number");
String s = String.valueOf( numScore );
EndScore.setText(s);
}
#SuppressWarnings("unused")
private void setButtonOnClickListeners(){
re_run.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
}
});
}
#Override
public void onBackPressed() {
// Do nothing
}
}
Put this line-
re_run = (Button) findViewById(R.id.retry);
Below
setContentView().
It looks as though the TextView EndScore (if you could in the future use lower case letters for variables) could not be found within the R.layout.gameover layout.
Be sure that the TextView is actually in that XML file.
Be sure that it is a TextView and not something else, like an EditText or something similar (although I think that would throw a different error).
EndScore is null according to the LogCat.

How to catch this exception in Android webview?

Due to a bug in Android 4.3, my app crashes when trying to load certain webpages in webview
The stack trace is like this:
09-16 14:16:48.221: E/AndroidRuntime(22487): FATAL EXCEPTION: WebViewCoreThread
09-16 14:16:48.221: E/AndroidRuntime(22487): java.lang.StringIndexOutOfBoundsException: length=0; index=-1
09-16 14:16:48.221: E/AndroidRuntime(22487): at java.lang.AbstractStringBuilder.indexAndLength(AbstractStringBuilder.java:212)
09-16 14:16:48.221: E/AndroidRuntime(22487): at java.lang.AbstractStringBuilder.charAt(AbstractStringBuilder.java:206)
09-16 14:16:48.221: E/AndroidRuntime(22487): at java.lang.StringBuffer.charAt(StringBuffer.java:346)
09-16 14:16:48.221: E/AndroidRuntime(22487): at com.android.org.bouncycastle.asn1.x509.X509NameTokenizer.nextToken(X509NameTokenizer.java:78)
09-16 14:16:48.221: E/AndroidRuntime(22487): at com.android.org.bouncycastle.asn1.x509.X509Name.<init>(X509Name.java:719)
09-16 14:16:48.221: E/AndroidRuntime(22487): at com.android.org.bouncycastle.asn1.x509.X509Name.<init>(X509Name.java:655)
09-16 14:16:48.221: E/AndroidRuntime(22487): at com.android.org.bouncycastle.asn1.x509.X509Name.<init>(X509Name.java:593)
09-16 14:16:48.221: E/AndroidRuntime(22487): at android.net.http.SslCertificate$DName.<init>(SslCertificate.java:379)
09-16 14:16:48.221: E/AndroidRuntime(22487): at android.net.http.SslCertificate.<init>(SslCertificate.java:189)
09-16 14:16:48.221: E/AndroidRuntime(22487): at android.net.http.SslCertificate.<init>(SslCertificate.java:178)
09-16 14:16:48.221: E/AndroidRuntime(22487): at android.webkit.BrowserFrame.setCertificate(BrowserFrame.java:1206)
09-16 14:16:48.221: E/AndroidRuntime(22487): at android.webkit.JWebCoreJavaBridge.nativeServiceFuncPtrQueue(Native Method)
09-16 14:16:48.221: E/AndroidRuntime(22487): at android.webkit.JWebCoreJavaBridge.handleMessage(JWebCoreJavaBridge.java:113)
09-16 14:16:48.221: E/AndroidRuntime(22487): at android.os.Handler.dispatchMessage(Handler.java:99)
09-16 14:16:48.221: E/AndroidRuntime(22487): at android.os.Looper.loop(Looper.java:137)
09-16 14:16:48.221: E/AndroidRuntime(22487): at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:814)
09-16 14:16:48.221: E/AndroidRuntime(22487): at java.lang.Thread.run(Thread.java:841)
In my webview I have onReceivedSslError, and onReceivedError methods overridden but none of them is able to catch this exception.
try{
webview.postUrl(url, EncodingUtils.getBytes(data, "BASE64"));
}
catch(Exception e){
System.out.println("Caught the exception!");
}
surrounding the call to postUrl with a try/catch block (as above) also doesn't catch the exception.
Is there any way to catch this exception so that I can display a meaningful error message instead of letting the app crash?
You may have to try setting up a global uncaught exception handler. You do this by extending Application and defining the uncaught exception handler within there. It would look something like this:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, final Throwable ex) {
// Custom code here to handle the error.
}
});
}
}
Just make sure you point to your custom Application class in your Manifest.
Give that a shot. hope it helps.
Regarding the question of why the exception could not be caught at activity level, the reason is that the exception occurred in a new thread, not in the try block.
The setDefaultUncaughtExceptionHandler sometimes does not work because the default handler could be overwritten by the later code.
And you are not able to recover from the exception in the UncaughtExceptionHandler.
All you can do is to log it and kill the process itself.

FTP connection java

I'm trying to upload the file to a server. What is the way for uploading a file to a server through FTP?
i wrote this class:
serverconnect.java:
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.SocketClient;
import org.apache.commons.net.ftp.FTPClient;
public class serverconnection
{
public FTPClient connectftp()
{
FTPClient ftp = null;
try {
ftp.connect("ftp://ftp.drivehq.com/");
ftp.login("zule", "*****");
// ftp.changeWorkingDirectory("/public");
// ftp.makeDirectory("200");
} catch (SocketException en) {
// TODO Auto-generated catch block
en.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ftp;
}
}
and this is the mainActivity ( only the relevant code):
import android.view.View;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
public class MainActivity extends Activity implements OnClickListener {
Button scan;
String contents;
String format;
TextView contentstext;
TextView formattext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----------------------FTP-------------
serverconnection ftpconnect =new serverconnection();
FTPClient ftp=ftpconnect.connectftp();
scan=(Button)findViewById(R.id.scanbutton);
.....
and when i install the app on my phone i get an error: "unfortanly your app must stopp..."
the new code:
public class MainActivity extends Activity implements OnClickListener {
Button scan;
String contents;
String format;
TextView contentstext;
TextView formattext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----------------------FTP-------------
//serverconnection ftpconnect =new serverconnection();
//SimpleFTP ftp=ftpconnect.connectftp();
SimpleFTP ftp = new SimpleFTP();
try {
ftp.connect("market.bugs3.com", 21, "u884282808", "lionetwork1");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
the new logcat:
09-16 13:43:31.131: E/AndroidRuntime(1203): FATAL EXCEPTION: main
09-16 13:43:31.131: E/AndroidRuntime(1203): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.market/com.example.market.MainActivity}: android.os.NetworkOnMainThreadException
09-16 13:43:31.131: E/AndroidRuntime(1203): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
09-16 13:43:31.131: E/AndroidRuntime(1203): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
09-16 13:43:31.131: E/AndroidRuntime(1203): at android.app.ActivityThread.access$600(ActivityThread.java:123)
09-16 13:43:31.131: E/AndroidRuntime(1203): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
09-16 13:43:31.131: E/AndroidRuntime(1203): at android.os.Handler.dispatchMessage(Handler.java:99)
09-16 13:43:31.131: E/AndroidRuntime(1203): at android.os.Looper.loop(Looper.java:137)
09-16 13:43:31.131: E/AndroidRuntime(1203): at android.app.ActivityThread.main(ActivityThread.java:4424)
09-16 13:43:31.131: E/AndroidRuntime(1203): at java.lang.reflect.Method.invokeNative(Native Method)
09-16 13:43:31.131: E/AndroidRuntime(1203): at java.lang.reflect.Method.invoke(Method.java:511)
09-16 13:43:31.131: E/AndroidRuntime(1203): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-16 13:43:31.131: E/AndroidRuntime(1203): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-16 13:43:31.131: E/AndroidRuntime(1203): at dalvik.system.NativeStart.main(Native Method)
09-16 13:43:31.131: E/AndroidRuntime(1203): Caused by: android.os.NetworkOnMainThreadException
09-16 13:43:31.131: E/AndroidRuntime(1203): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-16 13:43:31.131: E/AndroidRuntime(1203): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
09-16 13:43:31.131: E/AndroidRuntime(1203): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
09-16 13:43:31.131: E/AndroidRuntime(1203): at java.net.InetAddress.getAllByName(InetAddress.java:220)
09-16 13:43:31.131: E/AndroidRuntime(1203): at java.net.Socket.tryAllAddresses(Socket.java:108)
09-16 13:43:31.131: E/AndroidRuntime(1203): at java.net.Socket.<init>(Socket.java:177)
09-16 13:43:31.131: E/AndroidRuntime(1203): at java.net.Socket.<init>(Socket.java:149)
09-16 13:43:31.131: E/AndroidRuntime(1203): at org.jibble.simpleftp.SimpleFTP.connect(SimpleFTP.java:68)
09-16 13:43:31.131: E/AndroidRuntime(1203): at com.example.market.MainActivity.onCreate(MainActivity.java:31)
09-16 13:43:31.131: E/AndroidRuntime(1203): at android.app.Activity.performCreate(Activity.java:4465)
09-16 13:43:31.131: E/AndroidRuntime(1203): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
09-16 13:43:31.131: E/AndroidRuntime(1203): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
09-16 13:43:31.131: E/AndroidRuntime(1203): ... 11 more
Note: AsyncTask class was deprecated in API level 30. Please use java.util.concurrent instead.
The problem is the fact that you're trying to make a network call on your main thread. Which is not allowed on Android 3.0 or higher.
You should solve this by calling the FTP server on a different thread. A good way to do this is to use AsyncTask:
private class FtpTask extends AsyncTask<Void, Void, FTPClient> {
protected FTPClient doInBackground(Void... args) {
serverconnection ftpconnect =new serverconnection();
FTPClient ftp=ftpconnect.connectftp();
return ftp;
}
protected void onPostExecute(FTPClient result) {
Log.v("FTPTask","FTP connection complete");
ftpClient = result;
//Where ftpClient is a instance variable in the main activity
}
}
Then you can run this background thread using the following code in the main thread:
new FtpTask().execute();
EDIT:
If you want to pass parameters between the different methods, you can change the
AsyncTask<Void, Void, Void> superclass initialization.
For example AsyncTask<String, Double, Integer> will make it possible to pass a String variable to the doInBackground method, keep track of progress using a double and use a integer as the result type(the result type is the return type of doInBackground, which will be sent to onPostExecute as a parameter).

startActivity() forces closes my application

I cannot start a new activity no matter what I do.
I re-downloaded all Android SDKs again.
I re-downloaded Eclipse and installed ADT plugin again
Error Log
09-16 17:53:51.537: W/IInputConnectionWrapper(4661): getCursorCapsMode on inactive InputConnection
09-16 17:53:51.998: D/AndroidRuntime(4661): Shutting down VM
09-16 17:53:51.998: W/dalvikvm(4661): threadid=1: thread exiting with uncaught exception (group=0x41987300)
09-16 17:53:52.022: E/AndroidRuntime(4661): FATAL EXCEPTION: main
09-16 17:53:52.022: E/AndroidRuntime(4661): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.lays.decisong/com.lays.decisong.activities.GameActivity}: java.lang.NullPointerException
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.app.ActivityThread.access$600(ActivityThread.java:130)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.os.Handler.dispatchMessage(Handler.java:99)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.os.Looper.loop(Looper.java:137)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.app.ActivityThread.main(ActivityThread.java:4745)
09-16 17:53:52.022: E/AndroidRuntime(4661): at java.lang.reflect.Method.invokeNative(Native Method)
09-16 17:53:52.022: E/AndroidRuntime(4661): at java.lang.reflect.Method.invoke(Method.java:511)
09-16 17:53:52.022: E/AndroidRuntime(4661): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-16 17:53:52.022: E/AndroidRuntime(4661): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-16 17:53:52.022: E/AndroidRuntime(4661): at dalvik.system.NativeStart.main(Native Method)
09-16 17:53:52.022: E/AndroidRuntime(4661): Caused by: java.lang.NullPointerException
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:132)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:65)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.app.AlertDialog.<init>(AlertDialog.java:98)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.app.ProgressDialog.show(ProgressDialog.java:110)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.app.ProgressDialog.show(ProgressDialog.java:99)
09-16 17:53:52.022: E/AndroidRuntime(4661): at com.lays.decisong.activities.GameActivity$3.<init>(GameActivity.java:401)
09-16 17:53:52.022: E/AndroidRuntime(4661): at com.lays.decisong.activities.GameActivity.<init>(GameActivity.java:398)
09-16 17:53:52.022: E/AndroidRuntime(4661): at java.lang.Class.newInstanceImpl(Native Method)
09-16 17:53:52.022: E/AndroidRuntime(4661): at java.lang.Class.newInstance(Class.java:1319)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
09-16 17:53:52.022: E/AndroidRuntime(4661): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
Public key in DecisongApplication.java
public static final String PLAYERS_KEY = "com.lays.decisong.activities.Players";
Button Handler in InputActivity.java
App forces closes when startActivity() is called
public void startGame(View v) {
// check if there's more than one player
if (mPlayers.size() < 2) {
Log.i(TAG, "Only 1 player");
Toast.makeText(mContext, "At least 2 players needed to start game",
Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(this.getApplicationContext(), GameActivity.class);
intent.putStringArrayListExtra(DecisongApplication.PLAYERS_KEY, mPlayers);
startActivity(intent);
overridePendingTransition(R.anim.slide_up_incoming, R.anim.slide_up_outgoing);
}
Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lays.decisong"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="16" />
<supports-screens
android:anyDensity="true"
android:largeScreens="false"
android:normalScreens="true"
android:smallScreens="false"
android:xlargeScreens="false" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name="com.lays.decisong.DecisongApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.NoTitleBar" >
<activity android:name=".activities.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activities.InstructionsActivity"
android:noHistory="true" />
<activity
android:name=".activities.InputActivity"
android:noHistory="true" />
<activity
android:name=".activities.SettingsActivity"
android:noHistory="true" />
<activity
android:name=".activities.GameActivity"
android:noHistory="true" />
</application>
</manifest>
onCreate of GameActivity.java in com.lays.decisong.activities which never got called
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
// init rdio variables
mTrackQueue = new LinkedList<Track>();
if (mRdio == null) {
mRdio = new Rdio(DecisongApplication.RDIO_API_KEY,
DecisongApplication.RDIO_SECRET_KEY, null, null, this, this);
}
// init quiz variables
mListView = getListView();
mAllAlbums = new HashMap<String, Album>();
mChosenTracks = new ArrayList<Track>();
mAdapter = new TracksAdapter(this, mChosenTracks);
setListAdapter(mAdapter);
// init player variables
mCurrentRoundView = (TextView) findViewById(R.id.current_round);
mCurrentRound = INITIAL_ROUND;
mCurrentPlayerView = (TextView) findViewById(R.id.current_player);
mCurrentPlayer = INITIAL_PLAYER;
mPlayers = new ArrayList<Player>();
if (getIntent().hasExtra(DecisongApplication.PLAYERS_KEY)) {
ArrayList<String> players = getIntent().getStringArrayListExtra(DecisongApplication.PLAYERS_KEY);
for (String p : players) {
mPlayers.add(Player.create(p));
}
}
// setup game conditions
Collections.shuffle(mPlayers);
mCurrentPlayerView.setText(mPlayers.get(mCurrentPlayer).name);
}
09-16 17:53:52.022: E/AndroidRuntime(4661): at com.lays.decisong.activities.GameActivity$3.<init>(GameActivity.java:401)
09-16 17:53:52.022: E/AndroidRuntime(4661): at com.lays.decisong.activities.GameActivity.<init>(GameActivity.java:398)
Looks like you're trying to do some setup in your GameActivity's constructor, or initialise some fields before the activity's Context is fully initialised. You should really do all setup in onCreate(); don't use a constructor, and don't rely on the Context being usable until onCreate() is entered.

Categories