FTP connection java - 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).

Related

Getting a Runtime Exception trying to access sharedprefs for a boolean in android

I am using shared preferences to store data on whether or not a certain objective was completed for my class using a boolean shared preference. When I try and run this part of my code the logcat prints out this:
10-28 00:35:09.771: E/AndroidRuntime(429): FATAL EXCEPTION: main
10-28 00:35:09.771: E/AndroidRuntime(429): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.selectstartgo.physics281/com.selectstartgo.physics281.Grading}: java.lang.NullPointerException
10-28 00:35:09.771: E/AndroidRuntime(429): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
10-28 00:35:09.771: E/AndroidRuntime(429): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
10-28 00:35:09.771: E/AndroidRuntime(429): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-28 00:35:09.771: E/AndroidRuntime(429): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
10-28 00:35:09.771: E/AndroidRuntime(429): at android.os.Handler.dispatchMessage(Handler.java:99)
10-28 00:35:09.771: E/AndroidRuntime(429): at android.os.Looper.loop(Looper.java:123)
10-28 00:35:09.771: E/AndroidRuntime(429): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-28 00:35:09.771: E/AndroidRuntime(429): at java.lang.reflect.Method.invokeNative(Native Method)
10-28 00:35:09.771: E/AndroidRuntime(429): at java.lang.reflect.Method.invoke(Method.java:507)
10-28 00:35:09.771: E/AndroidRuntime(429): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-28 00:35:09.771: E/AndroidRuntime(429): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-28 00:35:09.771: E/AndroidRuntime(429): at dalvik.system.NativeStart.main(Native Method)
10-28 00:35:09.771: E/AndroidRuntime(429): Caused by: java.lang.NullPointerException
10-28 00:35:09.771: E/AndroidRuntime(429): at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:353)
10-28 00:35:09.771: E/AndroidRuntime(429): at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:348)
10-28 00:35:09.771: E/AndroidRuntime(429): at com.selectstartgo.physics281.PhysSharedPrefs.getSharPrefBoolean(PhysSharedPrefs.java:36)
10-28 00:35:09.771: E/AndroidRuntime(429): at com.selectstartgo.physics281.Grading.findCLevel(Grading.java:270)
10-28 00:35:09.771: E/AndroidRuntime(429): at com.selectstartgo.physics281.Grading.initialize(Grading.java:24)
10-28 00:35:09.771: E/AndroidRuntime(429): at com.selectstartgo.physics281.Grading.onCreate(Grading.java:16)
10-28 00:35:09.771: E/AndroidRuntime(429): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-28 00:35:09.771: E/AndroidRuntime(429): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
Here is my shared preference manager
package com.selectstartgo.physics281;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
public class PhysSharedPrefs {
public static void putSharPrefInt(Context context, String key, int value) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(context);
Editor edit = pref.edit();
edit.putInt(key, value);
edit.commit();
}
public static void putSharPrefBoolean(Context context, String key,
boolean value) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(context);
Editor edit = pref.edit();
edit.putBoolean(key, value);
edit.commit();
}
public static int getSharPrefInt(Context context, String key, int _default) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(context);
return pref.getInt(key, _default);
}
public static boolean getSharPrefBoolean(Context context, String key,
boolean _default) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(context);
return pref.getBoolean(key, _default);
}
}
And here's a chunk of code that is not working
if (PhysSharedPrefs.getSharPrefBoolean(MyApplication.getAppContext(),
"bKey101", false))
i++;
if (PhysSharedPrefs.getSharPrefBoolean(MyApplication.getAppContext(),
"bKey102", false))
i++;
if (PhysSharedPrefs.getSharPrefBoolean(MyApplication.getAppContext(),
"bKey103", false))
i++;
if (PhysSharedPrefs.getSharPrefBoolean(MyApplication.getAppContext(),
"bKey104", false))
And my MyApplication code looks like this:
package com.selectstartgo.physics281;
import android.app.Application;
import android.content.Context;
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
Thanks for any help I can get!
Since you have made a subclass of Application, for global access to the application context, have you remembered to edit your AndroidManifest.xml?
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:name="MyApplication"> <!-- This line -->
the error means MyApplication.getAppContext() ==null,you can check your code MyApplication
getAppContext() method ,

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.

Webserver can not be started

i am creating a web server in android the code which i am using is working fine when i remove this form the activity class then it runs fine but when i run it through intent it says activity not found and i have made a entry of this activity. this is my code..
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.security.acl.Owner;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
import dolphin.devlopers.com.R;
public class JHTTS extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook);
try{
InetAddress ownIP=InetAddress.getLocalHost();
System.out.println("IP of my Android := "+ownIP.getHostAddress());
Toast.makeText(getApplicationContext(), "Your ip is :: "+ownIP.getHostAddress(), 100).show();
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
}
try{
File documentRootDirectory = new File ("/sdcard/samer/");
JHTTP j = new JHTTP(documentRootDirectory,9000);
j.start();
Toast.makeText(getApplicationContext(), "Phishing Server Started!!", 5).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Jhttp classs:
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import android.util.Log;
public class JHTTP extends Thread {
private File documentRootDirectory;
private String indexFileName = "index.html";
private ServerSocket server;
private int numThreads = 50;
public JHTTP(File documentRootDirectory, int port,
String indexFileName) throws IOException {
if (!documentRootDirectory.isDirectory( )) {
throw new IOException(documentRootDirectory
+ " does not exist as a directory");
}
this.documentRootDirectory = documentRootDirectory;
this.indexFileName = indexFileName;
this.server = new ServerSocket(port);
}
public JHTTP(File documentRootDirectory, int port) throws IOException {
this(documentRootDirectory, port, "index.html");
}
public JHTTP(File documentRootDirectory) throws IOException {
this(documentRootDirectory, 80, "index.html");
}
public void run( ) {
try {
Process process = Runtime.getRuntime().exec("su");
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < numThreads; i++) {
Thread t = new Thread(
new RequestProcessor(documentRootDirectory, indexFileName));
t.start( );
}
System.out.println("Accepting connections on port " + server.getLocalPort( ));
System.out.println("Document Root: " + documentRootDirectory);
while (true) {
try {
Socket request = server.accept( );
request.setReuseAddress(true);
RequestProcessor.processRequest(request);
}
catch (IOException ex) {
}
}
}
public static void main(String[] args) {
// get the Document root
File docroot;
try {
docroot = new File("D:/");
}
catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Usage: java JHTTP docroot port indexfile");
return;
}
// set the port to listen on
try {
int port;
port = 9000;
JHTTP webserver = new JHTTP(docroot, port);
webserver.start( );
}
catch (IOException ex) {
System.out.println("Server could not start because of an "
+ ex.getClass( ));
System.out.println(ex);
}
}
}
Logcat:
07-26 21:51:33.447: E/AndroidRuntime(591): FATAL EXCEPTION: main
07-26 21:51:33.447: E/AndroidRuntime(591): java.lang.RuntimeException: Unable to start activity ComponentInfo{dolphin.devlopers.com/dolphin.developers.com.JHTTS}: android.content.ActivityNotFoundException: Unable to find explicit activity class {dolphin.devlopers.com/dolphin.developers.com.JHTTS$JHTTP}; have you declared this activity in your AndroidManifest.xml?
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.os.Handler.dispatchMessage(Handler.java:99)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.os.Looper.loop(Looper.java:123)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-26 21:51:33.447: E/AndroidRuntime(591): at java.lang.reflect.Method.invokeNative(Native Method)
07-26 21:51:33.447: E/AndroidRuntime(591): at java.lang.reflect.Method.invoke(Method.java:521)
07-26 21:51:33.447: E/AndroidRuntime(591): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-26 21:51:33.447: E/AndroidRuntime(591): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-26 21:51:33.447: E/AndroidRuntime(591): at dalvik.system.NativeStart.main(Native Method)
07-26 21:51:33.447: E/AndroidRuntime(591): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {dolphin.devlopers.com/dolphin.developers.com.JHTTS$JHTTP}; have you declared this activity in your AndroidManifest.xml?
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1404)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1378)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.Activity.startActivityForResult(Activity.java:2817)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.Activity.startActivity(Activity.java:2923)
07-26 21:51:33.447: E/AndroidRuntime(591): at dolphin.developers.com.JHTTS.onCreate(JHTTS.java:24)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-26 21:51:33.447: E/AndroidRuntime(591): ... 11 more
Manifest File:
<activity android:name="dolphin.developers.com.JHTTS"></activity>
new Logcat::
07-28 08:58:58.031: W/System.err(1687): java.net.BindException: Permission denied
07-28 08:58:58.031: W/System.err(1687): at org.apache.harmony.luni.platform.OSNetworkSystem.socketBindImpl(Native Method)
07-28 08:58:58.040: W/System.err(1687): at org.apache.harmony.luni.platform.OSNetworkSystem.bind(OSNetworkSystem.java:107)
07-28 08:58:58.050: W/System.err(1687): at org.apache.harmony.luni.net.PlainSocketImpl.bind(PlainSocketImpl.java:184)
07-28 08:58:58.060: W/System.err(1687): at java.net.ServerSocket.<init>(ServerSocket.java:138)
07-28 08:58:58.060: W/System.err(1687): at java.net.ServerSocket.<init>(ServerSocket.java:89)
07-28 08:58:58.060: W/System.err(1687): at dolphin.developers.com.JHTTP.<init>(JHTTP.java:28)
07-28 08:58:58.060: W/System.err(1687): at dolphin.developers.com.JHTTP.<init>(JHTTP.java:38)
07-28 08:58:58.070: W/System.err(1687): at dolphin.developers.com.JHTTS.onCreate(JHTTS.java:26)
07-28 08:58:58.070: W/System.err(1687): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-28 08:58:58.070: W/System.err(1687): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-28 08:58:58.070: W/System.err(1687): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-28 08:58:58.081: W/System.err(1687): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-28 08:58:58.081: W/System.err(1687): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-28 08:58:58.081: W/System.err(1687): at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 08:58:58.081: W/System.err(1687): at android.os.Looper.loop(Looper.java:123)
07-28 08:58:58.081: W/System.err(1687): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-28 08:58:58.100: W/System.err(1687): at java.lang.reflect.Method.invokeNative(Native Method)
07-28 08:58:58.100: W/System.err(1687): at java.lang.reflect.Method.invoke(Method.java:521)
07-28 08:58:58.100: W/System.err(1687): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-28 08:58:58.100: W/System.err(1687): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-28 08:58:58.100: W/System.err(1687): at dalvik.system.NativeStart.main(Native Method)
This code
Intent f = new Intent(JHTTS.this, JHTTP.class);
is to start an Activity as if JHHTP was an Activity but it's not, its a Thread inside the Activity. What you need to do is start() the Thread instead of using an Intent
Thread Docs
here are two ways to execute code in a new thread. You can either subclass Thread and overriding its run() method, or construct a new Thread and pass a Runnable to the constructor. In either case, the start() method must be called to actually execute the new Thread.
Instead of using Intent try something like
JHTTP jhttp = new JHTTP();
jhttp.start();

Android application stops unexpectedly when running

when testing my application in the emulator(I'm using Eclipse) it shows me "The application Counter(com.ian.counter) has stopped unexpectedly. Please try again." when running it. I've searched and searched for an answer but I've found none. Anyone know the problem?
Code:
package com.ian.counter;
import android.app.Activity;
import android.widget.TextView;
import android.os.Bundle;
import android.widget.Toast;
public class CounterActivity extends Activity {
/** Called when the activity is first created. */
TextView textView1 = (TextView) this.findViewById(R.id.textView1);
int count = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void Count(){
count ++;
textView1.setText(Integer.toString(count));
}
}
Logcat:
12-28 16:59:20.615: D/AndroidRuntime(353): Shutting down VM
12-28 16:59:20.686: W/dalvikvm(353): threadid=1: thread exiting with uncaught exception (group=0x40015560)
12-28 16:59:20.756: E/AndroidRuntime(353): FATAL EXCEPTION: main
12-28 16:59:20.756: E/AndroidRuntime(353): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.ian.counter/com.ian.counter.CounterActivity}: java.lang.NullPointerException
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.os.Handler.dispatchMessage(Handler.java:99)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.os.Looper.loop(Looper.java:123)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-28 16:59:20.756: E/AndroidRuntime(353): at java.lang.reflect.Method.invokeNative(Native Method)
12-28 16:59:20.756: E/AndroidRuntime(353): at java.lang.reflect.Method.invoke(Method.java:507)
12-28 16:59:20.756: E/AndroidRuntime(353): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-28 16:59:20.756: E/AndroidRuntime(353): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-28 16:59:20.756: E/AndroidRuntime(353): at dalvik.system.NativeStart.main(Native Method)
12-28 16:59:20.756: E/AndroidRuntime(353): Caused by: java.lang.NullPointerException
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.Activity.findViewById(Activity.java:1647)
12-28 16:59:20.756: E/AndroidRuntime(353): at com.ian.counter.CounterActivity.<init>(CounterActivity.java:10)
12-28 16:59:20.756: E/AndroidRuntime(353): at java.lang.Class.newInstanceImpl(Native Method)
12-28 16:59:20.756: E/AndroidRuntime(353): at java.lang.Class.newInstance(Class.java:1409)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
Any help is appreciated.
You're trying to set the textView1 variable before the layout has been set. You need to define it as a variable and then assign it in onCreate() after you've called setContentView(). Like this:
package com.ian.counter;
import android.app.Activity;
import android.widget.TextView;
import android.os.Bundle;
import android.widget.Toast;
public class CounterActivity extends Activity {
/** Called when the activity is first created. */
TextView textView1;
int count = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView) this.findViewById(R.id.textView1);
}
public void Count(){
count ++;
textView1.setText(Integer.toString(count));
}
}
Just copy and paste the above, that'll work just fine.
You should put this line
textView1 = (TextView) this.findViewById(R.id.textView1);
after
setContentView(R.layout.main);
and you just declare TextView in the begining
TextView textView1;
dont try to use findViewById(R.id.textView1); while declaraing instance variable as view does not exist at that point of time.
This is how your code should look like:
TextView textView1 = null;
int count = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textView1 = (TextView) findViewById(R.id.textView1);
}
public void Count(){
count ++;
textView1.setText(Integer.toString(count));
}

check if checkbox is checked return null pointer

I have this code for an expandable list, I want to have a checkbox in the childgroups of the list view, and check if one of the checkboxes is checked.
The problem is that when I check if the checkbox is checked I get a NULL Pointer Exception.
Can you please tell me whats wrong?
here's my code - I've edited the code to inflate a view of the child_row.xml that holds that checkbox but I still get that null pointer, what am I doing wrong?!?!
package send.Shift;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.ExpandableListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
public class Shifts extends ExpandableListActivity implements
OnCheckedChangeListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.list);
SimpleExpandableListAdapter expListAdapter = new SimpleExpandableListAdapter(
this, createGroupList(), R.layout.group_row,
new String[] { "Group Item" }, new int[] { R.id.row_name },
createChildList(), R.layout.child_row,
new String[] { "Sub Item" }, new int[] { R.id.grp_child });
getExpandableListView().setGroupIndicator(
getResources().getDrawable(R.drawable.expander_group));
ExpandableListView EX = (ExpandableListView) findViewById(android.R.id.list);
EX.setAdapter(expListAdapter);
final CheckBox childBox = (CheckBox) findViewById(R.id.childBOX);
final TextView choosenGroup = (TextView) findViewById(R.id.choosen);
LayoutInflater inflater = LayoutInflater.from(Shifts.this);
View view2 = inflater.inflate(R.layout.child_row, null);
childBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(childBox.isChecked() == true){
choosenGroup.setText("Shift Set");
}
}
});
}
Here is some of the Logcat log:
12-23 07:38:00.644: W/dalvikvm(880): threadid=1: thread exiting with uncaught exception (group=0x40015560)
12-23 07:38:00.654: E/AndroidRuntime(880): FATAL EXCEPTION: main
12-23 07:38:00.654: E/AndroidRuntime(880): java.lang.RuntimeException: Unable to start activity ComponentInfo{send.Shift/send.Shift.Shifts}: java.lang.NullPointerException
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.os.Handler.dispatchMessage(Handler.java:99)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.os.Looper.loop(Looper.java:123)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-23 07:38:00.654: E/AndroidRuntime(880): at java.lang.reflect.Method.invokeNative(Native Method)
12-23 07:38:00.654: E/AndroidRuntime(880): at java.lang.reflect.Method.invoke(Method.java:507)
12-23 07:38:00.654: E/AndroidRuntime(880): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-23 07:38:00.654: E/AndroidRuntime(880): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-23 07:38:00.654: E/AndroidRuntime(880): at dalvik.system.NativeStart.main(Native Method)
12-23 07:38:00.654: E/AndroidRuntime(880): Caused by: java.lang.NullPointerException
12-23 07:38:00.654: E/AndroidRuntime(880): at send.Shift.Shifts.onCreate(Shifts.java:41)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-23 07:38:00.654: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-23 07:38:00.654: E/AndroidRuntime(880): ... 11 more
If you get a nullpointer on a certain line, something on that line is null. If it is the if(childBox.isChecked() line, probably childBox is null. Hard to say without the stack, but most probable cause is the line where you retrieve that checkbox.
final CheckBox childBox = (CheckBox) findViewById(R.id.childBOX);
Might be returning null, and this could be for several reasons. It could be your id is childBox instead of childBOX. Or that it is not in R.layout.list.
The best thing you can do is start debugging. What line is the error. Find the object that is null. Find out why it is null and if that is expected or not.
Instead of checking the childBox.isChecked() you can use the isChecked value. So your code would look like this:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
choosenGroup.setText("Shift Set");
}
}
Check your layout list.xml I think this layout may is missing android:id="#+id/childBOX" for Check Box or android:id="#+id/choosen" for TextView
Check the folowin sample
<CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/childBOX"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/choosen"/>

Categories