I'm trying to upload an file via FTP from my Android Smartphone with my own app. I've got a done code, but it isn't working. Instead it throws me Exceptions in Logact. I hope you can help me.
Used Library: https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTP.html
My Code:
package com.florian.ftpupload;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import com.florian.ftpupload.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class UploadActivity extends Activity{
public static final String TAG = "Contacts";
public String host = "<serverip>";
public String username = "<username>";
public String password = "<password>";
public String database = "test.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Thread t = new Thread(new Runnable(){
#Override
public void run(){
try {
DatabaseUpload();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
Log.i(TAG, "thread started");
}
protected void DatabaseUpload() throws SocketException, IOException {
FTPClient ftp = new FTPClient();
ftp.connect(host);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)){
Toast.makeText(getApplicationContext(), "FTP server refused connection.", Toast.LENGTH_SHORT).show();
}
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
InputStream fis = new FileInputStream(database);
ftp.storeFile("test.txt", fis);
fis.close();
ftp.logout();
ftp.disconnect();
}
}
My LogCat Errors:
D/Genymotion( 56): Received Ping
I/ActivityManager( 366): START u0 {act=android.intent.action.MAIN cat= [android.
intent.category.LAUNCHER] flg=0x10200000 cmp=com.florian.ftpupload/.UploadActivi
ty} from pid 586
D/dalvikvm( 366): GC_CONCURRENT freed 805K, 16% free 7450K/8816K, paused 1ms+2m
s, total 20ms
I/ActivityManager( 366): Start proc com.florian.ftpupload for activity com.flor
ian.ftpupload/.UploadActivity: pid=1421 uid=10051 gids={50051, 1028}
I/qtaguid ( 366): Failed write_ctrl(s 1 10051) res=-1 errno=1
W/NetworkManagementSocketTagger( 366): setKernelCountSet(10051, 1) failed with
errno -1
E/dalvikvm( 1421): Could not find class 'org.apache.commons.net.ftp.FTPClient',
referenced from method com.florian.ftpupload.UploadActivity.DatabaseUpload
W/dalvikvm( 1421): VFY: unable to resolve new-instance 1557 (Lorg/apache/commons
/net/ftp/FTPClient;) in Lcom/florian/ftpupload/UploadActivity;
D/dalvikvm( 1421): VFY: replacing opcode 0x22 at 0x0000
D/dalvikvm( 1421): DexOpt: unable to opt direct call 0x2a97 at 0x02 in Lcom/flor
ian/ftpupload/UploadActivity;.DatabaseUpload
I/Contacts( 1421): thread started
W/dalvikvm( 1421): threadid=10: thread exiting with uncaught exception (group=0x
a614c908)
E/AndroidRuntime( 1421): FATAL EXCEPTION: Thread-122
E/AndroidRuntime( 1421): java.lang.NoClassDefFoundError: org.apache.commons.net.
ftp.FTPClient
E/AndroidRuntime( 1421): at com.florian.ftpupload.UploadActivity.Database
Upload(UploadActivity.java:55)
E/AndroidRuntime( 1421): at com.florian.ftpupload.UploadActivity$1.run(Up
loadActivity.java:40)
E/AndroidRuntime( 1421): at java.lang.Thread.run(Thread.java:856)
W/ActivityManager( 366): Force finishing activity com.florian.ftpupload/.Uplo
adActivity
D/libEGL ( 1421): loaded /system/lib/egl/libEGL_genymotion.so
D/ ( 1421): HostConnection::get() New Host Connection established 0xb7b1a
f98, tid 1421
D/libEGL ( 1421): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
D/libEGL ( 1421): loaded /system/lib/egl/libGLESv2_genymotion.so
I/ActivityManager( 366): START u0 {act=android.intent.action.MAIN cat= [android.
intent.category.LAUNCHER] flg=0x10200000 cmp=com.florian.ftpupload/.UploadActivi
ty} from pid 586
W/EGL_genymotion( 1421): eglSurfaceAttrib not implemented
D/OpenGLRenderer( 1421): Enabling debug mode 0
I/Contacts( 1421): thread started
W/dalvikvm( 1421): threadid=11: thread exiting with uncaught exception (group=0x
a614c908)
I/Process ( 1421): Sending signal. PID: 1421 SIG: 9
I/qtaguid ( 366): Failed write_ctrl(s 0 10051) res=-1 errno=1
W/NetworkManagementSocketTagger( 366): setKernelCountSet(10051, 0) failed with
errno -1
I/ActivityManager( 366): Process com.florian.ftpupload (pid 1421) has died.
I/WindowState( 366): WIN DEATH: Window{533f06e4 u0 com.florian.ftpupload/com.fl
orian.ftpupload.UploadActivity}
W/ActivityManager( 366): Force removing ActivityRecord{5348c488 u0 com.florian.
ftpupload/.UploadActivity}: app died, no saved state
I/WindowState( 366): WIN DEATH: Window{5343b134 u0 com.florian.ftpupload/com.fl
orian.ftpupload.UploadActivity}
W/EGL_genymotion( 586): eglSurfaceAttrib not implemented
W/InputMethodManagerService( 366): Window already focused, ignoring focus gain
of: com.android.internal.view.IInputMethodClient$Stub$Proxy#53330148 attribute=n
ull, token = android.os.BinderProxy#533c6a54
D/Genymotion( 56): Received Ping
I hope you understand my problem ;)
~Florian
Related
I am working on a project in android studio. The application is a client that connects to host written in c# using sockets. I am new to java this being my first project I am doing on my own. I am used with sockets in c# and in java I found a lot of similarities, but I encountered a strange problem: everything is fine until a new socket is initialized when the code execution seems to be interrupted. I will post the code than I will explain exactly what is happening.
First part, the main thread:
package com.example.alexandru.news;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Connection;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class login extends Activity {
EditText emadr;
EditText pasword;
Button log_in_butt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
log_in_butt = (Button) findViewById(R.id.login);
emadr= (EditText) findViewById(R.id.EmailAdr);
pasword= (EditText) findViewById(R.id.Password);
}
public void loginOnClick(View v)
{
final String mesaj=emadr.getText().toString()+"%"+pasword.getText().toString()+"%"+"^STOP^";
String[] perm={"android.permission.CAMERA"}; int a=200;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(perm,a);
}
com.example.alexandru.news.Connection log_in_connection=new com.example.alexandru.news.Connection(mesaj);
log_in_connection.start();
}
}
The connection class is a class I created in the same folder with the "log in" class(the main class). The code behind the Connection class:
package com.example.alexandru.news;
import android.content.Context;
import android.util.Xml;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
/**
* Created by Alexandru on 14.08.2016.
*/
public class Connection extends Thread {
String ip="some ip";
int port=60000;
String mesaj;
Socket soc;
public Connection(String mesaj) {
this.mesaj=mesaj;
}
#Override
public void run() {
try {
int a=2;
soc= new Socket(ip, port);
DataOutputStream outstream =new DataOutputStream(soc.getOutputStream());
byte[] buffer;
buffer = this.mesaj.getBytes("UTF-8");
outstream.write(buffer);
outstream.flush();
outstream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I run the app and I press the button everything is executed until the statement =new Socket(ip,port) is met when this happen the thread isn't executing anymore (I think). When I am debugging and the breakpoint is set before that problematic line everything works. When that line is highlighted and I press F8 the debugging tab says: "Application is running" and then pressing F8 again doesn't make any changes. If I press the "log in" button again nothing happens.
I am using a USB device to debug the app which is connected to the same network as the PC trough WiFi.No port forward is made. I worked with sockets in a project with my high school team before and we had a java client and a c# host and everything worked. But we were using the Emulator. I used all the ip addresses "ipconfig" gave me I changed the port, nothing happens. It doesn't work. I seems that I am the only one with this problem. Sorry for long post and lack of details.
This is the log:
08-17 12:09:38.875 30326-30326/com.example.alexandru.news D/libEGL: loaded /system/lib/egl/libEGL_MRVL.so
08-17 12:09:38.882 30326-30326/com.example.alexandru.news D/libEGL: loaded /system/lib/egl/libGLESv1_CM_MRVL.so
08-17 12:09:38.890 30326-30326/com.example.alexandru.news D/libEGL: loaded /system/lib/egl/libGLESv2_MRVL.so
08-17 12:09:38.898 30326-30326/com.example.alexandru.news D/GC: <tid=30326> OES20 ===> GC Version : GC Ver SS_rls_pxa988_JB42_R1_RC2_GC13.16
08-17 12:09:38.914 30326-30326/com.example.alexandru.news D/OpenGLRenderer: Enabling debug mode 0
08-17 12:09:38.929 30326-30326/com.example.alexandru.news D/WritingBuddyImpl: getCurrentWritingBuddyView()
08-17 12:09:39.054 30326-30326/com.example.alexandru.news D/v_gal: [tid=30326] gralloc_register_buffer: ===>Width = 480, Height = 800, surface = 0x60b55588
08-17 12:09:39.492 30326-30326/com.example.alexandru.news D/v_gal: [tid=30326] gralloc_register_buffer: ===>Width = 480, Height = 800, surface = 0x60e51d40
08-17 12:09:39.984 30326-30326/com.example.alexandru.news D/v_gal: [tid=30326] gralloc_register_buffer: ===>Width = 480, Height = 800, surface = 0x60ef84b8
08-17 12:14:05.617 30326-30350/com.example.alexandru.news D/Er: Eroare
08-17 12:14:17.765 30326-30350/com.example.alexandru.news W/System.err: java.net.SocketTimeoutException: failed to connect to /25.74.114.6 (port 60000) after 1000ms
08-17 12:14:17.765 30326-30350/com.example.alexandru.news W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:159)
08-17 12:14:17.781 30326-30350/com.example.alexandru.news W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:112)
08-17 12:14:17.796 30326-30350/com.example.alexandru.news W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-17 12:14:17.796 30326-30350/com.example.alexandru.news W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-17 12:14:17.796 30326-30350/com.example.alexandru.news W/System.err: at java.net.Socket.connect(Socket.java:842)
08-17 12:14:17.796 30326-30350/com.example.alexandru.news W/System.err: at com.example.alexandru.news.Connection.run(Connection.java:45)
08-17 12:14:17.828 30326-30350/com.example.alexandru.news D/dalvikvm: threadid=13: still suspended after undo (sc=1 dc=1)
08-17 12:14:17.828 30326-30330/com.example.alexandru.news D/dalvikvm: GC_CONCURRENT freed 360K, 17% free 8692K/10472K, paused 11ms+7ms, total 60ms
I'm trying to create a mock up of a workout app that tracks the sets and reps of an exercise.
Here is how the layout looks:
What I'm trying to do is when I press NEW it creates a new instance of Exercise is made. Exercise contains a list of Sets. Each set contains an integer variable called Reps. What I want to do is have an Exercise object created (in this instance a pullup) and then when I click NEW it will create a new Set to add to the list, and when I press the TAP button it will update the Rep value of the set. So eventually I want to end up with a list of Sets, each of which have a rep value.
For Example: Pullup : (5) (6) (5) (5) (3)
Which is a pullup with five sets, the first set had 5 reps, the second had 6 reps, the third had 5 reps and so on.
Here is the code I have written:
Sets.java
package com.example.soufin.pullupsv3;
/**
* Created by Soufin on 6/26/2015.
*/
public class Sets {
// private int _id;
private int _reps;
//constructor
//Sets(int reps) {
// setReps(reps);
//}
//getter
public int getReps()
{
return this._reps;
}
//setter
public void setReps(int reps)
{
this._reps = reps;
}
}
Exercise.java
package com.example.soufin.pullupsv3;
import java.util.List;
import com.example.soufin.pullupsv3.Sets;
/**
* Created by Soufin on 6/26/2015.
*/
public class Exercise {
//public int ID;
public String _name;
public List<Sets> _sets;
//getter
public String getName()
{
return this._name;
}
//setter
public void setName(String name)
{
this._name = name;
}
//getter
public List getSets() {return this._sets; }
// setter
//public void setSets(int reps){this._sets.add(new Sets());}
}
Workout.java (the main file)
package com.example.soufin.pullupsv3;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.R.*;
import com.example.soufin.pullupsv3.Sets;
import com.example.soufin.pullupsv3.Exercise;
import org.w3c.dom.Text;
public class Workout extends ActionBarActivity {
Exercise pullup;
Button wNew;
Button wTap;
Button wEnd;
TextView displayText;
int newIndex;
int tapCount;
int[] score = new int[5];
boolean flag = false;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workout);
pullup = new Exercise();
pullup.setName("Pullup");
wNew = (Button) findViewById(R.id.newSetButton);
wTap = (Button) findViewById(R.id.tapButton);
wEnd = (Button) findViewById(R.id.endWorkoutButton);
displayText = (TextView) findViewById(R.id.displayScore);
wNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Sets tempSet = new Sets(); // create new Set on click of mNew
wTap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tapCount += 1; // increment based on number of taps
}
});
tempSet.setReps(tapCount);
pullup._sets.add(tempSet); // add Set with reps (by taps) into List in Exercise
result = pullup.getSets().toString(); //store result
}
});
displayText.setText(result); //display result
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_workout, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Unfortunately, when I click the NEW button, the app crashes.
Here is what logcat says:
06-27 17:36:09.499 1236-1236/com.example.soufin.pullupsv3 D/dalvikvm﹕ Late-enabling CheckJNI
06-27 17:36:09.827 1236-1236/com.example.soufin.pullupsv3 I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
06-27 17:36:09.827 1236-1236/com.example.soufin.pullupsv3 W/dalvikvm﹕ VFY: unable to resolve virtual method 409: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
06-27 17:36:09.827 1236-1236/com.example.soufin.pullupsv3 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
06-27 17:36:09.831 1236-1236/com.example.soufin.pullupsv3 I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
06-27 17:36:09.831 1236-1236/com.example.soufin.pullupsv3 W/dalvikvm﹕ VFY: unable to resolve virtual method 431: Landroid/content/res/TypedArray;.getType (I)I
06-27 17:36:09.831 1236-1236/com.example.soufin.pullupsv3 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
06-27 17:36:09.919 1236-1236/com.example.soufin.pullupsv3 D/dalvikvm﹕ GC_FOR_ALLOC freed 140K, 7% free 3308K/3520K, paused 15ms, total 16ms
06-27 17:36:09.935 1236-1236/com.example.soufin.pullupsv3 D/dalvikvm﹕ GC_FOR_ALLOC freed 4K, 6% free 3524K/3744K, paused 7ms, total 8ms
06-27 17:36:10.011 1236-1236/com.example.soufin.pullupsv3 I/dalvikvm-heap﹕ Grow heap (frag case) to 5.927MB for 2536932-byte allocation
06-27 17:36:10.019 1236-1242/com.example.soufin.pullupsv3 D/dalvikvm﹕ GC_FOR_ALLOC freed <1K, 4% free 6001K/6224K, paused 6ms, total 6ms
06-27 17:36:10.151 1236-1236/com.example.soufin.pullupsv3 D/libEGL﹕ loaded /system/lib/egl/libEGL_xap.so
06-27 17:36:10.151 1236-1236/com.example.soufin.pullupsv3 D/eglCodecCommon﹕ TcpStream::connect() - management hostname is 10.71.34.101
06-27 17:36:10.151 1236-1236/com.example.soufin.pullupsv3 D/eglCodecCommon﹕ TcpStream::connect() - connecting host: 10.71.34.1
06-27 17:36:10.171 1236-1236/com.example.soufin.pullupsv3 D/﹕ HostConnection::get() New Host Connection established 0xb8786ca8, tid 1236
06-27 17:36:10.171 1236-1236/com.example.soufin.pullupsv3 D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_xap.so
06-27 17:36:10.175 1236-1236/com.example.soufin.pullupsv3 D/libEGL﹕ loaded /system/lib/egl/libGLESv2_xap.so
06-27 17:36:10.255 1236-1236/com.example.soufin.pullupsv3 W/EGL_xap﹕ eglSurfaceAttrib not implemented
06-27 17:36:10.255 1236-1236/com.example.soufin.pullupsv3 E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from GradienCache
06-27 17:36:10.255 1236-1236/com.example.soufin.pullupsv3 E/OpenGLRenderer﹕ MAX_TEXTURE_SIZE: 16384
06-27 17:36:10.259 1236-1236/com.example.soufin.pullupsv3 E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
06-27 17:36:10.259 1236-1236/com.example.soufin.pullupsv3 E/OpenGLRenderer﹕ MAX_TEXTURE_SIZE: 16384
06-27 17:36:10.259 1236-1236/com.example.soufin.pullupsv3 D/OpenGLRenderer﹕ Enabling debug mode 0
06-27 17:36:15.815 1236-1236/com.example.soufin.pullupsv3 W/EGL_xap﹕ eglSurfaceAttrib not implemented
06-27 17:36:19.395 1236-1236/com.example.soufin.pullupsv3 D/AndroidRuntime﹕ Shutting down VM
06-27 17:36:19.395 1236-1236/com.example.soufin.pullupsv3 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa4d6ab20)
06-27 17:36:19.403 1236-1236/com.example.soufin.pullupsv3 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.soufin.pullupsv3, PID: 1236
java.lang.NullPointerException
at com.example.soufin.pullupsv3.Workout$1.onClick(Workout.java:59)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
What am I doing wrong? And is the logic for my code alright?
Since the line with pullup._sets.add(tempSet) causes the error, there are two possible culprits: pullup or _sets could be null. Further inspection of your code suggests that the later one is causing the problem.
To fix the error, you should change
public List<Sets> _sets;
to
private List<Sets> _sets = new ArrayList<Sets>();
Note that I am making the _sets variable private. This means that other classes can only access this variable through the methods of the Exercise class. This is considered a good programming practice. I suggest you learn more about encapsulation and data hiding in order to understand this better.
More directly relevant to the error is that I am creating an ArrayList object for _sets to refer to. This is critical because otherwise _sets is null, which means it doesn't refer to any valid object, which then causes the NullPointerException which you saw.
Im trying to read a text file from the raw folder in res using final Scanner input = new Scanner(new File(R.raw.xmlsource)).useDelimiter("[\\;]+"); but it isn't reading because of the resource id being int in R.java file, my code is below
EDIT Made some changes to my code below, still doesn't run but using the debugger i can tell that it actually reads the file, the problem seems to be at String[] RssLinksArray = readLine.split("[\\;]+"); where the code terminates, i can't for the life of me figure out why. i'm attaching the logcat also.
Any help would be tremendously appreciated.
package com.simplerssreader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.util.List;
import java.util.Scanner;
import org.xmlpull.v1.XmlPullParserException;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
public class RssService extends IntentService
{
public static final String ITEMS = "items";
public static final String RECEIVER = "receiver";
public RssService()
{
super("RssService");
}
#Override
protected void onHandleIntent(Intent intent)
{
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
while ((readLine = br.readLine()) != null)
{
}
} catch (IOException e)
{
e.printStackTrace();
}
String[] RssLinksArray = readLine.split("[\\;]+");
final String RSS_LINK = RssLinksArray[0];
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
}
catch (XmlPullParserException e)
{
Log.w(e.getMessage(), e);
}
catch (IOException e)
{
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link)
{
try
{
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e)
{
Log.w(Constants.TAG, "Exception while retrieving the input stream", e);
return null;
}
}
}
LOGCAT
10-24 23:07:49.908: D/dalvikvm(1189): GC_FOR_ALLOC freed 101K, 9% free 2778K/3040K, paused 68ms, total 72ms
10-24 23:07:49.938: I/dalvikvm-heap(1189): Grow heap (frag case) to 3.939MB for 1127536-byte allocation
10-24 23:07:50.089: D/dalvikvm(1189): GC_FOR_ALLOC freed 2K, 7% free 3877K/4144K, paused 149ms, total 149ms
10-24 23:07:50.461: W/dalvikvm(1189): threadid=11: thread exiting with uncaught exception (group=0x41465700)
10-24 23:07:50.504: E/AndroidRuntime(1189): FATAL EXCEPTION: IntentService[RssService]
10-24 23:07:50.504: E/AndroidRuntime(1189): java.lang.NullPointerException
10-24 23:07:50.504: E/AndroidRuntime(1189): at com.simplerssreader.RssService.onHandleIntent(RssService.java:48)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.Handler.dispatchMessage(Handler.java:99)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.Looper.loop(Looper.java:137)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.HandlerThread.run(HandlerThread.java:61)
10-24 23:07:50.899: D/libEGL(1189): loaded /system/lib/egl/libEGL_emulation.so
10-24 23:07:50.940: D/(1189): HostConnection::get() New Host Connection established 0x2a1db628, tid 1189
10-24 23:07:51.078: D/libEGL(1189): loaded /system/lib/egl/libGLESv1_CM_emulation.so
10-24 23:07:51.279: D/libEGL(1189): loaded /system/lib/egl/libGLESv2_emulation.so
10-24 23:07:51.699: W/EGL_emulation(1189): eglSurfaceAttrib not implemented
10-24 23:07:51.729: D/OpenGLRenderer(1189): Enabling debug mode 0
10-24 23:07:51.769: I/Choreographer(1189): Skipped 85 frames! The application may be doing too much work on its main thread.
10-24 23:07:56.358: I/Choreographer(1189): Skipped 265 frames! The application may be doing too much work on its main thread.
InputStream inputStream = getResources().openRawResource(R.raw.xmlsource);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
I'm quite new to android development, I'm trying to develop a server-client application where the server is a simple java application that reads some text from a file and sends it using output stream. the client is an android application that reads this stream when clicking a button and displays it on a text view.
I'm using eclipse with ADK, and testing on an emulator here's how both codes look like:
Server:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Server {
/**
* #param args
* #throws IOException
* #throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException
{
System.out.println("***********Starting ***********");
ServerSocket servsock = new ServerSocket(12344);
System.out.println("Waiting...");
Socket sock = servsock.accept();
while (true)
{
System.out.println("Accepted connection : " + sock);
File myFile = new File ("source.txt");
while (true){
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
}
}
}
}
Client:
-MainActivity
package com.example.streamerclient;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Button ConnectBtn ;
#Override
public void onResume() {
super.onResume();
//setContentView(R.layout.activity_main);
System.out.println(" on resume ");
ConnectBtn = (Button)findViewById(R.id.ConnectButton);
ConnectBtn.setOnClickListener(this);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Connecting c = new Connecting();
}
}
-Connecting class
package com.example.streamerclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.app.Activity;
import android.widget.TextView;
public class Connecting extends Activity implements Runnable
{
private Socket sock;
private BufferedReader r;
private BufferedWriter out;
TextView Data;
public Connecting ()
{
Data = (TextView) findViewById(R.id.DataTextView);
Thread th = new Thread(this);
th.start();
}
#Override
public void run() {
try
{
System.out.println("trying to initiated ");
Data.setText("trying to initiated ");
sock = new Socket("10.0.2.2",12344);
System.out.println(" socket initiated ");
Data.setText(" socket initiated ");
r = new BufferedReader(new InputStreamReader(sock.getInputStream()));
Data.setText(" buffer reader initiated ");
System.out.println(" buffer reader initiated ");
out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
Data.setText(" buffer writer initiated ");
System.out.println(" buffer writer initiated ");
final String data = r.readLine();
Data.setText(" Data read is: \n"+data);
System.out.println(" Data read is: \n"+data);
}
catch (IOException ioe) { }
}
public void OnPause()
{
System.out.println(" paused");
try {
if (sock != null) {
sock.getOutputStream().close();
sock.getInputStream().close();
sock.close();
System.out.println(" everything is closed ");
}
} catch (IOException e) {}
}
}
I know I know, there are some parts of the code that are not used .. my next task is to have this application send commands to the server ... so I'm still experimenting.
when running the application on the emulator it stops before even displaying any of the GUI components. Any idea why ? Here's what the log file says
03-17 08:16:30.886: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:30.886: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:30.886: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:31.016: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:31.016: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:31.126: I/System.out(846): on resume
03-17 08:16:31.447: D/AndroidRuntime(846): Shutting down VM
03-17 08:16:31.447: W/dalvikvm(846): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
03-17 08:16:31.457: E/AndroidRuntime(846): FATAL EXCEPTION: main
03-17 08:16:31.457: E/AndroidRuntime(846): java.lang.RuntimeException: Unable to resume activity {com.example.streamerclient/com.example.streamerclient.MainActivity}: java.lang.NullPointerException
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2742)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2771)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2235)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.os.Handler.dispatchMessage(Handler.java:99)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.os.Looper.loop(Looper.java:137)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.main(ActivityThread.java:5039)
03-17 08:16:31.457: E/AndroidRuntime(846): at java.lang.reflect.Method.invokeNative(Native Method)
03-17 08:16:31.457: E/AndroidRuntime(846): at java.lang.reflect.Method.invoke(Method.java:511)
03-17 08:16:31.457: E/AndroidRuntime(846): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-17 08:16:31.457: E/AndroidRuntime(846): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-17 08:16:31.457: E/AndroidRuntime(846): at dalvik.system.NativeStart.main(Native Method)
03-17 08:16:31.457: E/AndroidRuntime(846): Caused by: java.lang.NullPointerException
03-17 08:16:31.457: E/AndroidRuntime(846): at com.example.streamerclient.MainActivity.onResume(MainActivity.java:20)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1185)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.Activity.performResume(Activity.java:5182)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2732)
03-17 08:16:31.457: E/AndroidRuntime(846): ... 12 more
thanks!
Try moving the contents of your entire onResume() to an onCreate() method. Always do the UI setup in onCreate(). Read this: Activity Lifecycle Management.
And take any further queries to stackoverflow :)
Cheers!
You are getting a NullPointerException on line 20 in MainActivity, check that line.
I think this question is better suited for stackoverflow
I'm developing an app for Android to download the pic from all the friends. I successfully made my app logging in. Now, I need to parse a JSON and download some of the pics. Here the sources:
FacebookPicDownloader (asynctask to download all the pics):
public class FacebookPicDownloader extends AsyncTask <String, Integer, Integer>{
Context context;
private final int MAX_BUFFER_SIZE = 2048;
String id;
int length;
public FacebookPicDownloader (Context context){
this.context = context;
}
//http://graph.facebook.com/ + userid + /picture?type=large to download the photos
#Override
protected Integer doInBackground(String... params) {
for (int i=0; i<params.length; i++){
try {
URL mUrl = new URL("http://graph.facebook.com/" + params[i] + "/picture?type=large");
HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
connection.connect();
length = connection.getContentLength();
int downloaded = 0;
File file = new File ("/sdcard/syncro/");
if (!file.exists() || !file.isDirectory()){
file.mkdir();
}
id = params[0];
file = new File ("/sdcard/syncro/" + id);
FileOutputStream fos = new FileOutputStream (file);
//Start downloading
InputStream stream = connection.getInputStream();
byte [] buffer = new byte [(length < MAX_BUFFER_SIZE) ? length : MAX_BUFFER_SIZE];
int read;
while ((read=stream.read(buffer)) != -1){
fos.write(buffer, 0, read);
downloaded += read;
}
fos.close();
} catch (Exception e){
return 2;
}
}
return 1;
}
Manager.java, another AsyncTask that calls FacebookPicDownloader
import java.util.ArrayList;
import org.json.*;
import com.gnufabio.syncro.util.Util;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.util.Log;
import com.facebook.android.*;
import com.gnufabio.syncro.util.*;
public class Manager extends AsyncTask<String, Integer, Integer>{
Context context;
Facebook facebook;
ProgressDialog dialog;
public void doStuff(Facebook facebook, Context context, String ... params){
this.context = context;
this.facebook = facebook;
this.execute(params);
}
#Override
protected void onPreExecute(){
dialog = ProgressDialog.show(context, "Wait" , " Loading. Please wait ... ", true);
dialog.setCancelable(false);
}
#Override
protected Integer doInBackground(String... params) {
String friendlist;
try {
friendlist = facebook.request("me/friends");
FileWriterThread filewriter = new FileWriterThread();
filewriter.writeFile(friendlist, "/sdcard/syncro/friends");
} catch (Exception e) {
friendlist = "";
}
String previous = "[NONE]";
ArrayList validContacts = new ArrayList<String>();
Cursor nameCur = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
if (display != null && !(display.contains(previous) || display.equalsIgnoreCase(previous)) && display.contains(" ")){
Log.d("SYNCRO", "Valid contact found: " + display);
validContacts.add(display);
previous = display;
}
}
nameCur.close();
try {
ArrayList idToDownload = new ArrayList <String>();
JSONArray jFriendList = new JSONArray(new JSONObject(friendlist).getString("data"));
for (int i = 0; i < jFriendList.length(); i++){
JSONObject jFriend = jFriendList.getJSONObject(i);
for (int y = 0; y < validContacts.toArray().length; y++){
if (jFriend.getString("name").equals((String)(validContacts.get(y)))){
String id = jFriend.getString("id");
Log.d("SYNCRO", "Adding pic for id \"" + id + "\"");
idToDowload.add(id);
}
}
}
FacebookPicDownloader downloader = new FacebookPicDownloader(context);
downloader.execute((String[]) idToDownload.toArray());
} catch (JSONException e) {
Log.d("SYNCRO", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Integer result){
dialog.dismiss();
}
}
The problem is that it downloads just the first pic, and then the app crashes...here the logcat:
D/szipinf ( 7785): Initializing inflate state
E/AndroidRuntime( 7735): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime( 7735): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime( 7735): at android.os.AsyncTask$3.done(AsyncTask.java:200)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
E/AndroidRuntime( 7735): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
E/AndroidRuntime( 7735): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
E/AndroidRuntime( 7735): at java.lang.Thread.run(Thread.java:1019)
E/AndroidRuntime( 7735): Caused by: java.lang.ClassCastException: [Ljava.lang.Object;
E/AndroidRuntime( 7735): at com.gnufabio.syncro.Manager.doInBackground(Manager.java:78)
E/AndroidRuntime( 7735): at com.gnufabio.syncro.Manager.doInBackground(Manager.java:1)
E/AndroidRuntime( 7735): at android.os.AsyncTask$2.call(AsyncTask.java:185)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
E/AndroidRuntime( 7735): ... 4 more W/ActivityManager( 541): Force finishing activity com.gnufabio.syncro/.SuperSyncronizerActivity D/szipinf ( 7797): Initializing inflate state D/szipinf ( 7797): Initializing zlib to inflate D/dalvikvm( 7797): GC_CONCURRENT freed 224K, 44% free 3519K/6215K, external 0K/0K, paused 3ms+3ms
E/WindowManager( 7735): Activity com.gnufabio.syncro.SuperSyncronizerActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4051c538 that was originally added here
E/WindowManager( 7735): android.view.WindowLeaked: Activity com.gnufabio.syncro.SuperSyncronizerActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4051c538 that was originally added here
E/WindowManager( 7735): at android.view.ViewRoot.<init>(ViewRoot.java:260)
E/WindowManager( 7735): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
E/WindowManager( 7735): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
E/WindowManager( 7735): at android.view.Window$LocalWindowManager.addView(Window.java:424)
E/WindowManager( 7735): at android.app.Dialog.show(Dialog.java:241)
E/WindowManager( 7735): at android.app.ProgressDialog.show(ProgressDialog.java:110)
E/WindowManager( 7735): at android.app.ProgressDialog.show(ProgressDialog.java:93)
E/WindowManager( 7735): at com.gnufabio.syncro.Manager.onPreExecute(Manager.java:36)
E/WindowManager( 7735): at android.os.AsyncTask.execute(AsyncTask.java:391)
E/WindowManager( 7735): at com.gnufabio.syncro.Manager.doStuff(Manager.java:31)
E/WindowManager( 7735): at com.gnufabio.syncro.SuperSyncronizerActivity$2.onClick(SuperSyncronizerActivity.java:73)
E/WindowManager( 7735): at android.view.View.performClick(View.java:2486)
E/WindowManager( 7735): at android.view.View$PerformClick.run(View.java:9130)
E/WindowManager( 7735): at android.os.Handler.handleCallback(Handler.java:587)
E/WindowManager( 7735): at android.os.Handler.dispatchMessage(Handler.java:92)
E/WindowManager( 7735): at android.os.Looper.loop(Looper.java:130)
E/WindowManager( 7735): at android.app.ActivityThread.main(ActivityThread.java:3694)
E/WindowManager( 7735): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager( 7735): at java.lang.reflect.Method.invoke(Method.java:507)
E/WindowManager( 7735): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
E/WindowManager( 7735): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
E/WindowManager( 7735): at dalvik.system.NativeStart.main(Native Method) D/dalvikvm( 7797): GC_CONCURRENT freed 171K, 41% free 3888K/6535K, external 0K/0K, paused 3ms+4ms
Thanks to anyone will help me.
The crash is caused by this code: (String[]) idToDownload.toArray().
Try creating a new String array instead of using the cast:
Replace the line
downloader.execute((String[]) idToDownload.toArray());
By:
String[] stringArray= new String[idToDownload.size()];
idToDownload.toArray(stringArray);
downloader.execute(stringArray);
KR