AsyncTask doesn't execute when trying to clean HTML with HtmlCleaner - java

I'm trying to clean HTML with HtmlCleaner using AsyncTask. This is the code:
private class cleanHtml extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
try {
HtmlCleaner cleaner = new HtmlCleaner();
String url = "https://www.easistent.com/urniki/263/razredi/16515";
TagNode node = cleaner.clean(new URL(url));
CleanerProperties props = cleaner.getProperties();
new PrettyXmlSerializer(props).writeToFile(node, "cleaned.xml", "utf-8");
Log.i("TAG", "Executing AsyncTask");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
I'm executing AsyncTask in onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new cleanHtml().execute();
}//End of onCreate
However, nothing happens. As you can see I put log.i inside the AsyncTask to see if it is executing r not and I never see the log.i message inside logcat. What could I be doing wrong? Also, where in my phone will "cleaned.xml" appear? Since I didn't set any kind of destination folder.
Logcat (info):
09-25 20:23:31.739: W/System.err(19078): java.io.FileNotFoundException: /cleaned.xml: open failed: EROFS (Read-only file system)
09-25 20:23:31.747: W/System.err(19078): at libcore.io.IoBridge.open(IoBridge.java:409)
09-25 20:23:31.747: W/System.err(19078): at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
09-25 20:23:31.747: W/System.err(19078): at java.io.FileOutputStream.<init>(FileOutputStream.java:128)
09-25 20:23:31.755: W/System.err(19078): at java.io.FileOutputStream.<init>(FileOutputStream.java:117)
09-25 20:23:31.755: W/System.err(19078): at org.htmlcleaner.Serializer.writeToFile(Serializer.java:131)
09-25 20:23:31.755: W/System.err(19078): at org.htmlcleaner.Serializer.writeToFile(Serializer.java:142)
09-25 20:23:31.755: W/System.err(19078): at com.whizzapps.stpsurniki.ScheudeleWithDesign$cleanHtml.doInBackground(ScheudeleWithDesign.java:36)
09-25 20:23:31.755: W/System.err(19078): at com.whizzapps.stpsurniki.ScheudeleWithDesign$cleanHtml.doInBackground(ScheudeleWithDesign.java:1)
09-25 20:23:31.755: W/System.err(19078): at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-25 20:23:31.755: W/System.err(19078): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-25 20:23:31.755: W/System.err(19078): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-25 20:23:31.755: W/System.err(19078): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-25 20:23:31.755: W/System.err(19078): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-25 20:23:31.755: W/System.err(19078): at java.lang.Thread.run(Thread.java:841)
09-25 20:23:31.755: W/System.err(19078): Caused by: libcore.io.ErrnoException: open failed: EROFS (Read-only file system)
09-25 20:23:31.755: W/System.err(19078): at libcore.io.Posix.open(Native Method)
09-25 20:23:31.755: W/System.err(19078): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
09-25 20:23:31.763: W/System.err(19078): at libcore.io.IoBridge.open(IoBridge.java:393)

The AsncTask is executed. But the execution is not brought to an end because of an exception.
You are getting a FileNotFoundEcxeption in this line:
new PrettyXmlSerializer(props).writeToFile(node, "cleaned.xml", "utf-8");
which is caught by your catch-block preventing your app from crashing.
The Exception could be caused by:
The path to the "cleaned.xml" file not being correct.
Typos int he filename.

Related

java.io.IOException: Prepare failed.: status=0x1 in Android

I tried to play a file in ListView with mediaPlayer class.
Like this:
public void initializeViews() {
Intent intent = getIntent();
String fName = intent.getStringExtra("fileName");
fileName = (TextView) findViewById(R.id.fileName);
duration = (TextView) findViewById(R.id.songDuration);
seekbar = (SeekBar) findViewById(R.id.seekBar);
playBtn = (ImageButton) findViewById(R.id.media_play);
try {
mediaPlayer = new android.media.MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(fName);
mediaPlayer.prepare();
}
catch (IOException e) {
e.printStackTrace();
}
fileName.setText(fName.substring(fName.lastIndexOf("/") + 1));
finalTime = mediaPlayer.getDuration();
seekbar.setOnSeekBarChangeListener(mOnSeek);
seekbar.setMax((int) finalTime);
seekbar.setClickable(true);
mediaPlayer.start();
timeElapsed = mediaPlayer.getCurrentPosition();
seekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 200);
}
I search on the internet, and the most question is check the path to file, but the fName got the full path to a file. But I don't know it shows exception:
java.io.IOException: Prepare failed.: status=0x1
All log when application occurs exception:
E/MediaPlayer: error (1, -2147483648)
W/System.err: java.io.IOException: Prepare failed.: status=0x1
W/System.err: at android.media.MediaPlayer.prepare(Native Method)
W/System.err: at kr.co.composer.callrecord.media.AudioPlayer.initializeViews(AudioPlayer.java:56)
W/System.err: at kr.co.composer.callrecord.media.AudioPlayer.onCreate(AudioPlayer.java:42)
W/System.err: at android.app.Activity.performCreate(Activity.java:5231)
W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:135)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:136)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5001)
W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
W/System.err: at dalvik.system.NativeStart.main(Native Method)
E/MediaPlayer: Attempt to call getDuration without a valid mediaplayer
E/MediaPlayer: error (-38, 0)
E/MediaPlayer: start called in state 0
E/MediaPlayer: error (-38, 0)
E/MediaPlayer: Error (-38,0)
E/MediaPlayer: Error (-38,0)
W/EGL_genymotion: eglSurfaceAttrib not implemented
stop called in state 0
error (-38, 0)
stop called in state 0
error (-38, 0)
Error (-38,0)
Error (-38,0)
stop called in state 0
error (-38, 0)
Error (-38,0)
pause called in state 0
error (-38, 0)
Possible caused by reading permission. Fix by inserting the permission in manifest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

App closing when defining a Uri Android

When I execute this code it works fine in my emulator (even saves the image), but it closes the application on my phone (nexus 5)
When I set a try catch around the Uri line the program does not crash (but then again its null value could also have no influence on the code below it)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode== 0 && resultCode == Activity.RESULT_OK) {
Bitmap x = (Bitmap) data.getExtras().get("data");
userImage.setImageBitmap(x);
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "profileimage");
values.put(Images.Media.BUCKET_ID, "profileimage");
values.put(Images.Media.DESCRIPTION, "profile Image");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(uri);
x.compress(Bitmap.CompressFormat.JPEG, 70, outstream);
outstream.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
}
Cheers!
EDIT:
(sorry for my inactivity - new android phone that logs :D)
This is the error log:
03-28 15:33:51.230: E/Permission Denial: writing com.android.providers.media.MediaProvider uri content://media/ext ActivityFilt[ 03-28 15:33:51.231 10005:10005 D/AndroidRuntime(10005): Shutting down VM
03-28 15:33:51.238: E/AndroidRuntime(10005): FATAL EXCEPTION: main
03-28 15:33:51.238: E/AndroidRuntime(10005): Process: com.td.tdabslidingmenu, PID: 10005
03-28 15:33:51.238: E/AndroidRuntime(10005): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.td.tdabslidingmenu/com.td.tdabslidingmenu.MainActivity}: java.lang.NullPointerException: uri
03-28 15:33:51.238: E/AndroidRuntime(10005): at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
03-28 15:33:51.238: E/AndroidRuntime(10005): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
03-28 15:33:51.238: E/AndroidRuntime(10005): at android.app.ActivityThread.-wrap16(ActivityThread.java)
03-28 15:33:51.238: E/AndroidRuntime(10005): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
03-28 15:33:51.238: E/AndroidRuntime(10005): at android.os.Handler.dispatchMessage(Handler.java:102)
03-28 15:33:51.238: E/AndroidRuntime(10005): at android.os.Looper.loop(Looper.java:148)
03-28 15:33:51.238: E/AndroidRuntime(10005): at android.app.ActivityThread.main(ActivityThread.java:5417)
03-28 15:33:51.238: E/AndroidRuntime(10005): at java.lang.reflect.Method.invoke(Native Method)
03-28 15:33:51.238: E/AndroidRuntime(10005): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-28 15:33:51.238: E/AndroidRuntime(10005): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-28 15:33:51.238: E/AndroidRuntime(10005): Caused by: java.lang.NullPointerException: uri
03-28 15:33:51.238: E/AndroidRuntime(10005): at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
03-28 15:33:51.238: E/AndroidRuntime(10005): at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:922)
03-28 15:33:51.238: E/AndroidRuntime(10005): at android.content.ContentResolver.openOutputStream(ContentResolver.java:702)
03-28 15:33:51.238: E/AndroidRuntime(10005): at android.content.ContentResolver.openOutputStream(ContentResolver.java:678)
03-28 15:33:51.238: E/AndroidRuntime(10005): at com.td.tdabslidingmenu.MainActivity.onActivityResult(MainActivity.java:263)
03-28 15:33:51.238: E/AndroidRuntime(10005): at android.app.Activity.dispatchActivityResult(Activity.java:6456)
03-28 15:33:51.238: E/AndroidRuntime(10005): at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
03-28 15:33:51.238: E/AndroidRuntime(10005): ... 9 more
Which Android version is your Nexus 5 running? If it's Marshmallow (or the N preview), chances are it's a permission problem caused by the Media.EXTERNAL_CONTENT_URI part of your code.

Android app crashes when initializing AndroidAsyncHttp

As I understood (from here) the LoopJ AndroidAsyncHttp does not uses the UI Thread, therefore i can execute its methods in the Main Thread.
but when i intilize a new instance of AsyncHttpClient the app crashes
(exception: java.lang.IllegalStateException: Could not execute method of the activity )
code :
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Send(View view) {
EditText editText = (EditText) findViewById(R.id.editText1);
String str = editText.getText().toString();
TextView div = (TextView) findViewById(R.id.textView1);
div.setText(str);
//crash
AsyncHttpClient client = new AsyncHttpClient();
}
#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);
}
}
Error:
09-25 09:58:07.427: W/dalvikvm(2514): threadid=1: thread exiting with uncaught exception (group=0xb1cb2b20)
09-25 09:58:07.477: E/AndroidRuntime(2514): FATAL EXCEPTION: main
09-25 09:58:07.477: E/AndroidRuntime(2514): Process: com.example.mysecondapp, PID: 2514
09-25 09:58:07.477: E/AndroidRuntime(2514): java.lang.IllegalStateException: Could not execute method of the activity
09-25 09:58:07.477: E/AndroidRuntime(2514): at android.view.View$1.onClick(View.java:3823)
09-25 09:58:07.477: E/AndroidRuntime(2514): at android.view.View.performClick(View.java:4438)
09-25 09:58:07.477: E/AndroidRuntime(2514): at android.view.View$PerformClick.run(View.java:18422)
09-25 09:58:07.477: E/AndroidRuntime(2514): at android.os.Handler.handleCallback(Handler.java:733)
09-25 09:58:07.477: E/AndroidRuntime(2514): at android.os.Handler.dispatchMessage(Handler.java:95)
09-25 09:58:07.477: E/AndroidRuntime(2514): at android.os.Looper.loop(Looper.java:136)
09-25 09:58:07.477: E/AndroidRuntime(2514): at android.app.ActivityThread.main(ActivityThread.java:5017)
09-25 09:58:07.477: E/AndroidRuntime(2514): at java.lang.reflect.Method.invokeNative(Native Method)
09-25 09:58:07.477: E/AndroidRuntime(2514): at java.lang.reflect.Method.invoke(Method.java:515)
09-25 09:58:07.477: E/AndroidRuntime(2514): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-25 09:58:07.477: E/AndroidRuntime(2514): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-25 09:58:07.477: E/AndroidRuntime(2514): at dalvik.system.NativeStart.main(Native Method)
09-25 09:58:07.477: E/AndroidRuntime(2514): Caused by: java.lang.reflect.InvocationTargetException
09-25 09:58:07.477: E/AndroidRuntime(2514): at java.lang.reflect.Method.invokeNative(Native Method)
09-25 09:58:07.477: E/AndroidRuntime(2514): at java.lang.reflect.Method.invoke(Method.java:515)
09-25 09:58:07.477: E/AndroidRuntime(2514): at android.view.View$1.onClick(View.java:3818)
09-25 09:58:07.477: E/AndroidRuntime(2514): ... 11 more
09-25 09:58:07.477: E/AndroidRuntime(2514): Caused by: java.lang.NoClassDefFoundError: com.loopj.android.http.AsyncHttpClient
09-25 09:58:07.477: E/AndroidRuntime(2514): at com.example.mysecondapp.MainActivity.Send(MainActivity.java:46)
09-25 09:58:07.477: E/AndroidRuntime(2514): ... 14 more
You're getting a NoClassDefFoundError for com.loopj.android.http.AsyncHttpClient
If you are running from an IDE, make sure to add exported="true" to the classpathentry for android-async-http-1.4.6.jar in your .classpath file.
I had to move the jar file to the "libs" folder and then add the jar to the project... thanks everyone!

string to integer conversion in android

I have a problem in String conversion here i pass a value through intent and access through bundle and now i want to convert into integer but it is showing force stopped ..........
MainActivity code:
btn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent in=new Intent(MainActivity.this,second.class);
in.putExtra("id", "12");
startActivity(in);
}
});
secondActivity code:
Bundle extras = getIntent().getExtras();
id=extras.getString("id");
btn=(Button)findViewById(R.id.button1);
tv=(TextView)findViewById(R.id.value);
btn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
int myid=Integer.parseInt(id);
//tv.setText(myid);
Toast.makeText(getApplicationContext(), myid,Toast.LENGTH_SHORT).show();
}
});
LogCat:>
09-25 18:21:52.045: E/AndroidRuntime(1555): FATAL EXCEPTION: main
09-25 18:21:52.045: E/AndroidRuntime(1555): android.content.res.Resources$NotFoundException: String resource ID #0xc
09-25 18:21:52.045: E/AndroidRuntime(1555): at android.content.res.Resources.getText(Resources.java:230)
09-25 18:21:52.045: E/AndroidRuntime(1555): at android.widget.Toast.makeText(Toast.java:265)
09-25 18:21:52.045: E/AndroidRuntime(1555): at com.example.convert.second$1.onClick(second.java:34)
09-25 18:21:52.045: E/AndroidRuntime(1555): at android.view.View.performClick(View.java:4204)
09-25 18:21:52.045: E/AndroidRuntime(1555): at android.view.View$PerformClick.run(View.java:17355)
09-25 18:21:52.045: E/AndroidRuntime(1555): at android.os.Handler.handleCallback(Handler.java:725)
09-25 18:21:52.045: E/AndroidRuntime(1555): at android.os.Handler.dispatchMessage(Handler.java:92)
09-25 18:21:52.045: E/AndroidRuntime(1555): at android.os.Looper.loop(Looper.java:137)
09-25 18:21:52.045: E/AndroidRuntime(1555): at android.app.ActivityThread.main(ActivityThread.java:5041)
09-25 18:21:52.045: E/AndroidRuntime(1555): at java.lang.reflect.Method.invokeNative(Native Method)
09-25 18:21:52.045: E/AndroidRuntime(1555): at java.lang.reflect.Method.invoke(Method.java:511)
09-25 18:21:52.045: E/AndroidRuntime(1555): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-25 18:21:52.045: E/AndroidRuntime(1555): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-25 18:21:52.045: E/AndroidRuntime(1555): at dalvik.system.NativeStart.main(Native Method)
Don't do TextView.setText(int), do TextView.setText(String), that means skipping the conversation completely. There are multiple inputs setText() can take, as shown here.
What's happening in your case is that since you are converting your value over to an integer, you're inadvertently calling public final void setText (int resid) which assumes the integer passed into it is the R.id value of something in your strings.xml file.
That's clearly not what you want to be doing, so you can do one of two things to fix it:
Replace your setText() with setText("" + myid);
Stop converting your value to an int!

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).

Categories