FTP connection drivehq - java

I created an Android app which has an FTP connection, however when I start the app it says "unfortunately your app must stopped", and I can't find the problem.
I tried to enter local passive mode however it didn't help me, I also tried to run the app on my phone however it gave me the same message.
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
Button scan;
String contents;
String format;
TextView contentstext;
TextView formattext;
FTPClient ftpclient;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----------------------FTP-------------
new FtpTask().execute();
//ftpclient.enterLocalPassiveMode();
try {
ftpclient.changeToParentDirectory();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scan=(Button)findViewById(R.id.scanbutton);
contentstext=(TextView)findViewById(R.id.contentstext);
formattext=(TextView)findViewById(R.id.formattext);
scan.setOnClickListener(this);
}
private class FtpTask extends AsyncTask<Void, Void, FTPClient> {
protected FTPClient doInBackground(Void... args) {
FTPClient ftp = new FTPClient ();
try {
ftp.connect("ftp.drivehq.com");
ftp.login("zule","****");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ftp;
}
protected void onPostExecute(FTPClient result) {
Log.v("FTPTask","FTP connection complete");
ftpclient = result;
}
}
here is the logcat:
09-17 12:11:30.319: E/AndroidRuntime(1113): FATAL EXCEPTION: main
09-17 12:11:30.319: E/AndroidRuntime(1113): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.market/com.example.market.MainActivity}: java.lang.NullPointerException
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.ActivityThread.access$600(ActivityThread.java:123)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.os.Handler.dispatchMessage(Handler.java:99)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.os.Looper.loop(Looper.java:137)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.ActivityThread.main(ActivityThread.java:4424)
09-17 12:11:30.319: E/AndroidRuntime(1113): at java.lang.reflect.Method.invokeNative(Native Method)
09-17 12:11:30.319: E/AndroidRuntime(1113): at java.lang.reflect.Method.invoke(Method.java:511)
09-17 12:11:30.319: E/AndroidRuntime(1113): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-17 12:11:30.319: E/AndroidRuntime(1113): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-17 12:11:30.319: E/AndroidRuntime(1113): at dalvik.system.NativeStart.main(Native Method)
09-17 12:11:30.319: E/AndroidRuntime(1113): Caused by: java.lang.NullPointerException
09-17 12:11:30.319: E/AndroidRuntime(1113): at com.example.market.MainActivity.onCreate(MainActivity.java:32)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.Activity.performCreate(Activity.java:4465)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
09-17 12:11:30.319: E/AndroidRuntime(1113): ... 11 more

Look at the stack trace. It says you have a NullPointerException on line 32.
If I counted right, that's this line:
ftpclient.changeToParentDirectory();
Notice that your class member ftpClient is not instantiated; so it's still null when you try to call changeToParentDirectory() on it.
Adding ftpClient = new FtpClient( ... ) somewhere before this call should solve your problem. Add the correct parameters for the dots.

Related

Android: Using getResources might be causing my app to crash

I don't know why this is causing my app to crash. I have instantiated 3 class variables to point to the color values I created in my colors.xml file. I have been experimenting, and the code that is commented out here seems to be causing the error "appName has stopped working"
protected int m_nDarkColor = R.color.dark;
//protected int m_nDarkColor = getResources().getColor(R.color.dark);
protected int m_nLightColor = R.color.light;
//protected int m_nLightColor = getResources().getColor(R.color.light);
protected int m_nTextColor = R.color.text;
//protected int m_nTextColor = getResources().getColor(R.color.text);
private boolean isDark = false; //To alternate between colors.
This is the method that is using the class variables on top. If I use the uncommented class variables in the setBackgroundColor() methods, the color is the same gray shade no matter what I change the color values to (that is why I commented those out too), so I tried setBackgroundColor(getResources()get.Color(R.color.dark) and it fixed the problem, but it made my class variables useless. I don't mean to be picky, I am just confused why when I set the class variable to point to my colors values in colors.xml, it causes my app to stop working or the smae gray color, but when I pass it to the setBackgroundColor method it works just fine.
`
protected void addJoke(String strJoke) {
android.widget.TextView display = new android.widget.TextView(this);
display.setText(strJoke); //Sets the text on display.
display.setTextSize(16); //Increases the font size of the text.
display.setTextColor(getResources().getColor(R.color.text));
//display.setTextColor(m_nTextColor);
if(!isDark)
{
display.setBackgroundColor(getResources().getColor(R.color.dark));
//display.setBackgroundColor(m_nDarkColor);
isDark = true;
}
else if(isDark)
{
display.setBackgroundColor(getResources().getColor(R.color.light));
//display.setBackgroundColor(m_nLightColor);
isDark = false;
}
m_vwJokeLayout.addView(display); //Adds the view to the layout.
}
This is all the red from LogCat
09-17 20:47:25.852: E/AndroidRuntime(11212): FATAL EXCEPTION: main
09-17 20:47:25.852: E/AndroidRuntime(11212): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{edu.calpoly.android.lab2/edu.calpoly.android.lab2.SimpleJokeList}: java.lang.NullPointerException
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.os.Handler.dispatchMessage(Handler.java:99)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.os.Looper.loop(Looper.java:137)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.ActivityThread.main(ActivityThread.java:5039)
09-17 20:47:25.852: E/AndroidRuntime(11212): at java.lang.reflect.Method.invokeNative(Native Method)
09-17 20:47:25.852: E/AndroidRuntime(11212): at java.lang.reflect.Method.invoke(Method.java:511)
09-17 20:47:25.852: E/AndroidRuntime(11212): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-17 20:47:25.852: E/AndroidRuntime(11212): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-17 20:47:25.852: E/AndroidRuntime(11212): at dalvik.system.NativeStart.main(Native Method)
09-17 20:47:25.852: E/AndroidRuntime(11212): Caused by: java.lang.NullPointerException
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.content.ContextWrapper.getResources(ContextWrapper.java:89)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78)
09-17 20:47:25.852: E/AndroidRuntime(11212): at edu.calpoly.android.lab2.SimpleJokeList.<init>(SimpleJokeList.java:34)
09-17 20:47:25.852: E/AndroidRuntime(11212): at java.lang.Class.newInstanceImpl(Native Method)
09-17 20:47:25.852: E/AndroidRuntime(11212): at java.lang.Class.newInstance(Class.java:1319)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
09-17 20:47:25.852: E/AndroidRuntime(11212): ... 11 more
Final Note: The way the code is set up now works, the colors come out right and the app runs on my device, the error is only caused when I switch the commented code with the uncommented code. This is my first question on here, so I hope it hasn't been asked before and I formatted it correctly, thanks for help!
Imagine like this: R.color.dark is like a pointer point to the value of color(Certainly not a real pointer like C language). And you use getResources().getColor(R.color.dark) method to get the real value of color.
Do a test:
Log.d("Color", "Value of \"R.color.gray\" is: " + R.color.gray);
Log.d("Color", "Value of \"getResources().getColor(R.color.gray)\" is: " + getResources().getColor(R.color.gray));
Here is the output in logCat:
09-18 11:07:17.458 32359-32359/com.ch.summerrunner D/Color﹕ Value of "R.color.gray" is: 2131099651
09-18 11:07:17.458 32359-32359/com.ch.summerrunner D/Color﹕ Value of "getResources().getColor(R.color.gray)" is: -2144128205
the value -2144128205 means the real color in Android system.
May this help you.
-----------add--------------
I understand what you mean.
Why your app crashes?
Because getResources() method return null.
But why it return null when you call it to set the class variable?
Long Story.
getResource() is a interface of Context and implement by ContextWrapper. Like this :
#Override
public Resources getResources()
{
return mBase.getResources();
}
But the Constructor of ContextThemeWrapper(Subclasses of ContextWrapper) is :
public ContextThemeWrapper() {
super(null);
}
and
public ContextThemeWrapper(Context base, int themeres) {
super(base);
mBase = base;
mThemeResource = themeres;
}
You can see that the mBase of ContextWrapper may be null.
This is the Constructor of Activity(Subclasses of ContextThemeWrapper):
public Activity ()
Activity Constructor
We did not pass a context to Activity, so when did ContextWrapper initialize mBase ?
When system create/start an Activity, system pass a mBase instance to Activity by attachBaseContext(Context base) method of Activity.
This is why you get NULL when you call getResources() to set the class variable.
You call the method too early. Call getResources() in onCreate() of later.
There may be some mistakes in this answer, if you wanna know more, read the source:
frameworks/base/core/java/android/app/ActivityThread.java
You are calling getResources() too early in the activity lifecycle.
The activity is usable as a Context only in onCreate() or later. Instance initialization (<init> in your stacktrace) is too early. Move the getResources() and such to onCreate() or later.
I added iconics to app then after remove that from application I comment the code on attachBaseContext. App started to give this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
After I remove attachBaseContext completely, everything is fine.
#Override
protected void attachBaseContext(Context newBase)
{
//super.attachBaseContext(IconicsContextWrapper.wrap(newBase));
}

Java application reading name from a file

I am stuck trying to reading from a .txt file a name and last name into a java application, I have tryed on first method with AssetManager but my application Crash when I enter it.
The second method is with inputstream but I get 3 errors:
Description Resource Path Location Type
ByteArrayOutputStream cannot be resolved to a type MainActivity.java /MyInfo/src/com/example/myinfo line 64 Java Problem
ByteArrayOutputStream cannot be resolved to a type MainActivity.java /MyInfo/src/com/example/myinfo line 64 Java Problem
dummytext cannot be resolved or is not a field MainActivity.java /MyInfo/src/com/example/myinfo line 55 Java Problem
MainActivity.java
package com.example.myinfo;
import java.io.IOException;
import java.io.InputStream;
import android.os.Bundle;
import android.content.res.AssetManager;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
TextView name = (TextView) findViewById(R.id.name);
AssetManager assetManager = getAssets();
InputStream input;
try {
input = assetManager.open("info.txt");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
String text = new String(buffer);
nume.setText(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
TextView dummytext = (TextView) findViewById(R.id.dummytext);
dummytext.setText(readText());
}
private String readText() {
InputStream inputStream = getResources().openRawResource(R.raw.dummytext);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while(i!=-1){
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
}catch (IOException e){
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
and my XML is this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.myinfo.MainActivity$PlaceholderFragment" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="87dp"
android:text="Adauga Fisier" />
<TextView
android:id="#+id/dummytext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/nume"
android:layout_below="#+id/nume"
android:layout_marginTop="29dp"
android:text="Prenume"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/button1"
android:layout_marginRight="14dp"
android:layout_marginTop="65dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
I don't understand what I did wrong.
When I run the code that is now in Comments I notice that I get in Logcat NullPointerException.
LogCat:
04-07 10:06:11.298: I/dalvikvm(275): Could not find method android.content.pm.PackageManager.getActivityLogo, referenced from method android.support.v7.internal.widget.ActionBarView.<init>
04-07 10:06:11.298: W/dalvikvm(275): VFY: unable to resolve virtual method 318: Landroid/content/pm/PackageManager;.getActivityLogo (Landroid/content/ComponentName;)Landroid/graphics/drawable/Drawable;
04-07 10:06:11.298: D/dalvikvm(275): VFY: replacing opcode 0x6e at 0x008b
04-07 10:06:11.308: I/dalvikvm(275): Could not find method android.content.pm.ApplicationInfo.loadLogo, referenced from method android.support.v7.internal.widget.ActionBarView.<init>
04-07 10:06:11.308: W/dalvikvm(275): VFY: unable to resolve virtual method 314: Landroid/content/pm/ApplicationInfo;.loadLogo (Landroid/content/pm/PackageManager;)Landroid/graphics/drawable/Drawable;
04-07 10:06:11.308: D/dalvikvm(275): VFY: replacing opcode 0x6e at 0x0099
04-07 10:06:11.318: D/dalvikvm(275): VFY: dead code 0x008e-0092 in Landroid/support/v7/internal/widget/ActionBarView;.<init> (Landroid/content/Context;Landroid/util/AttributeSet;)V
04-07 10:06:11.318: D/dalvikvm(275): VFY: dead code 0x009c-00a0 in Landroid/support/v7/internal/widget/ActionBarView;.<init> (Landroid/content/Context;Landroid/util/AttributeSet;)V
04-07 10:06:11.488: D/AndroidRuntime(275): Shutting down VM
04-07 10:06:11.488: W/dalvikvm(275): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-07 10:06:11.498: E/AndroidRuntime(275): FATAL EXCEPTION: main
04-07 10:06:11.498: E/AndroidRuntime(275): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myinfo/com.example.myinfo.MainActivity}: java.lang.NullPointerException
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.os.Handler.dispatchMessage(Handler.java:99)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.os.Looper.loop(Looper.java:123)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-07 10:06:11.498: E/AndroidRuntime(275): at java.lang.reflect.Method.invokeNative(Native Method)
04-07 10:06:11.498: E/AndroidRuntime(275): at java.lang.reflect.Method.invoke(Method.java:521)
04-07 10:06:11.498: E/AndroidRuntime(275): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-07 10:06:11.498: E/AndroidRuntime(275): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-07 10:06:11.498: E/AndroidRuntime(275): at dalvik.system.NativeStart.main(Native Method)
04-07 10:06:11.498: E/AndroidRuntime(275): Caused by: java.lang.NullPointerException
04-07 10:06:11.498: E/AndroidRuntime(275): at com.example.myinfo.MainActivity.onCreate(MainActivity.java:42)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-07 10:06:11.498: E/AndroidRuntime(275): ... 11 more
04-07 10:06:18.688: I/Process(275): Sending signal. PID: 275 SIG: 9
use this code
`InputStream input;
AssetManager assetManager = getAssets();
try {
input = assetManager.open("helloworld.txt");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
String text = new String(buffer);
dummytext.setText(text);
} catch (IOException e) {
e.printStackTrace();
}
`
This code open an InputStream for the file from assets manager, get size from file content, allocate byte buffer with this size and read file in this buffer, after this create new string from buffer and set this string to your textview

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();

Getting a DialogFragment to instantiate

I am new to Android.
Trying to show a dialog on press of a button like below using DialogFragments
File : Dialog2/LoginDialog.java
package com.kartnet.Dialog2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.LayoutInflater;
import android.widget.Toast;
import android.content.Context;
import android.app.Dialog;
import android.content.DialogInterface;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.util.Log;
public class LoginDialog extends DialogFragment
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder ad_builder = new AlertDialog.Builder(getActivity());
//ad_builder.setMessage(R.string.login_dialog);
DialogInterface.OnClickListener ad_listener =
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg1, int id) {
final String tag = "CustomDlg";
Log.d(tag, id + " clicked");
}
};
ad_builder.setTitle(R.string.btn_dialog_custom_title);
LayoutInflater linf = getActivity().getLayoutInflater();
ad_builder.setView(linf.inflate(R.layout.dialog_signin, null));
ad_builder.setNegativeButton("Cancel", ad_listener);
ad_builder.setPositiveButton("Ok", ad_listener);
return ad_builder.create();
}
}
File : Dialog2/Dialog2App.java
package com.kartnet.Dialog2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.LayoutInflater;
import android.widget.Toast;
import android.content.Context;
import android.app.Dialog;
import android.content.DialogInterface;
import android.app.DialogFragment;
import android.app.AlertDialog;
import android.util.Log;
public class Dialog2App extends Activity
{
/* Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void displayDialogCustom(View v)
{
LoginDialog ld = new LoginDialog(); /*<<=== FAILS with runtime exception */
// ld.show(getFragmentManager(), "login_dialog");
} /* displayCustomDialog */
}
Why should it fail at runtime, with no errors during compile time? Also, since both files are declared to be in the same package (com.kartnet.Dialog2), is there anything special I need to get these two java files to be in the application?
Here is what the error displayed
I/ActivityManager( 69): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.kartnet.Dialog2/.Dialog2App } from pid 210
I/ActivityManager( 69): Start proc com.kartnet.Dialog2 for activity com.kartnet.Dialog2/.Dialog2App: pid=1328 uid=10034 gids={1015}
W/dalvikvm( 1328): Unable to resolve superclass of Lcom/kartnet/Dialog2/LoginDialog; (7)
W/dalvikvm( 1328): Link of class 'Lcom/kartnet/Dialog2/LoginDialog;' failed
E/dalvikvm( 1328): Could not find class 'com.kartnet.Dialog2.LoginDialog', referenced from method com.kartnet.Dialog2.Dialog2App.displayDialogCustom
W/dalvikvm( 1328): VFY: unable to resolve new-instance 25 (Lcom/kartnet/Dialog2/LoginDialog;) in Lcom/kartnet/Dialog2/Dialog2App;
D/dalvikvm( 1328): VFY: replacing opcode 0x22 at 0x0000
D/dalvikvm( 1328): VFY: dead code 0x0002-0005 in Lcom/kartnet/Dialog2/Dialog2App;.displayDialogCustom (Landroid/view/View;)V
I/ActivityManager( 69): Displayed com.kartnet.Dialog2/.Dialog2App: +1s956ms
D/dalvikvm( 317): GC_EXPLICIT freed 19K, 55% free 2588K/5703K, external 1625K/2137K, paused 3208ms
D/AndroidRuntime( 1328): Shutting down VM
W/dalvikvm( 1328): threadid=1: thread exiting with uncaught exception (group=0x40015560)
E/AndroidRuntime( 1328): FATAL EXCEPTION: main
E/AndroidRuntime( 1328): java.lang.IllegalStateException: Could not execute method of the activity
E/AndroidRuntime( 1328): at android.view.View$1.onClick(View.java:2144)
E/AndroidRuntime( 1328): at android.view.View.performClick(View.java:2485)
E/AndroidRuntime( 1328): at android.view.View$PerformClick.run(View.java:9080)
E/AndroidRuntime( 1328): at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime( 1328): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 1328): at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime( 1328): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime( 1328): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 1328): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 1328): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime( 1328): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime( 1328): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 1328): Caused by: java.lang.reflect.InvocationTargetException
E/AndroidRuntime( 1328): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 1328): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 1328): at android.view.View$1.onClick(View.java:2139)
E/AndroidRuntime( 1328): ... 11 more
E/AndroidRuntime( 1328): Caused by: java.lang.NoClassDefFoundError: com.kartnet.Dialog2.LoginDialog
E/AndroidRuntime( 1328): at com.kartnet.Dialog2.Dialog2App.displayDialogCustom(Dialog2App.java:104)
E/AndroidRuntime( 1328): ... 14 more
Based on the attached log, it appears you're trying to run the code on an older device which does not offer native support to Fragments:
Unable to resolve superclass of Lcom/kartnet/Dialog2/LoginDialog;
Above basically means that android.app.DialogFragment could not be resolved, which will happen on pre-Honeycomb (< Android 3.0 / API level 11) devices. You were probably looking for the backwards compatible Fragment classes that are part of the support library (in the android.support.v4.app.* package).
To migrate your code to the classes in the support libary, you should:
Set up the support library.
Change all android.app.DialogFragment references to android.support.v4.app.DialogFragment (and also any other Fragment classes you may be using).
Change your Activity to a FragmentActivity (also located in the support libary).
Use this dialog manager to display simple dialogs.
public class AlertDialogManager {
/**
* Function to display simple Alert Dialog
* #param context - application context
* #param title - alert dialog title
* #param message - alert message
* #param status - success/failure (used to set icon)
* - pass null if you don't want icon
* */
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
}
In your activity you can use this
alert.showAlertDialog(MainActivity.this,"Header","Message", false);
Try this:
Properties->Java Build Path->Order and Export and check Android Private Libraries
You can try to create the dialog before you return it with
Dialog d = ad_builder.create();
return d;
to see if it fail to create the dialog.
DialogFragment are singletons, so you cannot do:
LoginDialog ld = new LoginDialog(); /*<<=== FAILS with runtime exception */
you should use LoginDialog.instantiate(...) method

Unable to fetch and display JSON in Android

I am building a complex application however I am having an isolated problem. My Android application class UserPage.java should be able to fetch a String from a webpage and then pass that over to the layout and display it accordingly.
UserPage.java
package com.example.ams;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
public class UserPage extends Activity {
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userpage);
String json = getStudents();
//System.out.println(json);
TextView datazer = (TextView) findViewById(R.id.data);
datazer.setText(json);
}
public String getStudents(){
HttpResponse response = null;
//String classID = "CSD2334";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://localhost:8080/de.vogella.jersey.first/resources/hello/ids/CSD2334"));
response = client.execute(request);
System.out.println(response.toString());
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response.toString();
}
}
The layout - userpage.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
The content fetched from the web
[{"student_id":3,"student_name":"Dite Gashi","w1mo":"1","w1tue":"0","w1wed":0,"w1thu":0,"w1fri":1},{"student_id":4,"student_name":"Vullnet Dyla","w1mo":"2","w1tue":"2","w1wed":1,"w1thu":0,"w1fri":0},{"student_id":5,"student_name":"Edon Ymeri","w1mo":"0","w1tue":"0","w1wed":0,"w1thu":0,"w1fri":2},{"student_id":6,"student_name":"Ilir Kelmendi","w1mo":"2","w1tue":"0","w1wed":2,"w1thu":0,"w1fri":0}]
The error I am getting is quite generic and I can't seem to find information anywhere
03-30 17:36:15.074: E/AndroidRuntime(1458): FATAL EXCEPTION: main
03-30 17:36:15.074: E/AndroidRuntime(1458): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ams/com.example.ams.UserPage}: android.os.NetworkOnMainThreadException
03-30 17:36:15.074: E/AndroidRuntime(1458): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
03-30 17:36:15.074: E/AndroidRuntime(1458): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
03-30 17:36:15.074: E/AndroidRuntime(1458): at android.app.ActivityThread.access$600(ActivityThread.java:123)
03-30 17:36:15.074: E/AndroidRuntime(1458): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
03-30 17:36:15.074: E/AndroidRuntime(1458): at android.os.Handler.dispatchMessage(Handler.java:99)
03-30 17:36:15.074: E/AndroidRuntime(1458): at android.os.Looper.loop(Looper.java:137)
03-30 17:36:15.074: E/AndroidRuntime(1458): at android.app.ActivityThread.main(ActivityThread.java:4424)
03-30 17:36:15.074: E/AndroidRuntime(1458): at java.lang.reflect.Method.invokeNative(Native Method)
03-30 17:36:15.074: E/AndroidRuntime(1458): at java.lang.reflect.Method.invoke(Method.java:511)
03-30 17:36:15.074: E/AndroidRuntime(1458): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-30 17:36:15.074: E/AndroidRuntime(1458): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-30 17:36:15.074: E/AndroidRuntime(1458): at dalvik.system.NativeStart.main(Native Method)
03-30 17:36:15.074: E/AndroidRuntime(1458): Caused by: android.os.NetworkOnMainThreadException
03-30 17:36:15.074: E/AndroidRuntime(1458): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
03-30 17:36:15.074: E/AndroidRuntime(1458): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
03-30 17:36:15.074: E/AndroidRuntime(1458): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
03-30 17:36:15.074: E/AndroidRuntime(1458): at java.net.InetAddress.getAllByName(InetAddress.java:220)
03-30 17:36:15.074: E/AndroidRuntime(1458): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
03-30 17:36:15.074: E/AndroidRuntime(1458): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-30 17:36:15.074: E/AndroidRuntime(1458): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-30 17:36:15.074: E/AndroidRuntime(1458): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-30 17:36:15.074: E/AndroidRuntime(1458): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-30 17:36:15.074: E/AndroidRuntime(1458): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-30 17:36:15.074: E/AndroidRuntime(1458): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-30 17:36:15.074: E/AndroidRuntime(1458): at com.example.ams.UserPage.getStudents(UserPage.java:44)
03-30 17:36:15.074: E/AndroidRuntime(1458): at com.example.ams.UserPage.onCreate(UserPage.java:31)
03-30 17:36:15.074: E/AndroidRuntime(1458): at android.app.Activity.performCreate(Activity.java:4465)
03-30 17:36:15.074: E/AndroidRuntime(1458): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-30 17:36:15.074: E/AndroidRuntime(1458): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
03-30 17:36:15.074: E/AndroidRuntime(1458): ... 11 more
03-30 17:36:15.363: I/dalvikvm(1458): threadid=3: reacting to signal 3
03-30 17:36:15.434: I/dalvikvm(1458): Wrote stack traces to '/data/anr/traces.txt'
03-30 17:36:15.814: I/dalvikvm(1458): threadid=3: reacting to signal 3
03-30 17:36:15.834: I/dalvikvm(1458): Wrote stack traces to '/data/anr/traces.txt'
Any help or pointers would be highly appreciated,
D
You are running a http call on the main thread and that causes the error.
response = client.execute(request);
The above code should run on a new Thread.
Your should have something like:
new Thread( new Runnable() {
#Override
public void run() {
HttpResponse response = null;
//String classID = "CSD2334";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://localhost:8080/de.vogella.jersey.first/resources/hello/ids/CSD2334"));
response = client.execute(request);
System.out.println(response.toString());
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response.toString();
}
}).start();
And if you want to make updates to a UI component you should run the code into:
runOnUiThread(new Runnable() {
#Override
public void run() {
// runs on the UI thread so update UI here
}
});
You should read more about threads on android
Your current code runs, as mentioned, on the uiThread. Consider using either an asynctask or a class which extends Thread. There is a lot of questions regarding this, by doing a quick Google search, so I feel that an example would be too much.

Categories