Webserver can not be started - java

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

Related

How to connect an Android application to a MySQL database?

I am very new at programming Android applications, So please help me.
I want to connect my application to a MySQL database.
But I get an error that crashes the application. Here is the error in LogCat:
07-26 12:32:47.785: E/AndroidRuntime(276): FATAL EXCEPTION: main
07-26 12:32:47.785: E/AndroidRuntime(276): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.massar_parent/com.example.parent.MainActivity}: java.lang.NullPointerException
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.os.Handler.dispatchMessage(Handler.java:99)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.os.Looper.loop(Looper.java:123)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-26 12:32:47.785: E/AndroidRuntime(276): at java.lang.reflect.Method.invokeNative(Native Method)
07-26 12:32:47.785: E/AndroidRuntime(276): at java.lang.reflect.Method.invoke(Method.java:521)
07-26 12:32:47.785: E/AndroidRuntime(276): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-26 12:32:47.785: E/AndroidRuntime(276): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-26 12:32:47.785: E/AndroidRuntime(276): at dalvik.system.NativeStart.main(Native Method)
07-26 12:32:47.785: E/AndroidRuntime(276): Caused by: java.lang.NullPointerException
07-26 12:32:47.785: E/AndroidRuntime(276): at com.example.massar_parent.MainActivity.onCreate(MainActivity.java:44)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
And the code in MainActivity.java
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
//private TextView texte = null;
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt.setText("Connexion...");
// Appeler la méthode pour récupérer les données JSON
txt.setText(getServerData(strURL));
}
// Mettre l'adresse du script PHP
// Attention localhost ou 127.0.0.1 ne fonctionnent pas. Mettre l'adresse IP
// local.
public static final String strURL = "http://localhost/massar/connection.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("NomEleve", "L"));
// Envoie de la commande http
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strURL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convertion de la requête en string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// Parse les données JSON
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
// Affichage ID_ville et Nom_ville dans le LogCat
Log.i("log_tag", "CNE: " + json_data.getInt("CNE") + ", NomEleve: "
+ json_data.getString("NomEleve"));
// Résultats de la requête
returnString += "\n\t" + jArray.getJSONObject(i);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
And here is the code AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.massar_parent"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I hope someone can help :/
There are two mistakes I can see:
TextView is not initialized. Do you know findViewById()?
You have made a web call directly on main UI thread which would cause an issue!
You have a field txt:
TextView txt;
which is declared, but it is never set to a value. Therefore, when you try to use it here:
txt.setText("Connexion...");
it throws an exception because it still has the value null.
If you have declared the TextView in your layout (e.g. with <TextView android:id="#+id/the_identifier_of_your_textview"), you need to assign it like this, immediately after calling setContentView:
txt = (TextView)this.FindViewById(R.id.the_identifier_of_your_textview);

AChartEngine - Charts with data from parse.com won't display

I would like to create applications forming charts based on data from parse.com. I have read some examples and tutorials but still have problem with displaying charts. Below is my code:
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import java.util.ArrayList;
public class LineGraph {
public ArrayList<Integer> dataArray;
XYMultipleSeriesDataset dataset;
XYMultipleSeriesRenderer renderer;
public static boolean ClickEnabled = true;
public Intent getIntent(Context context) {
ArrayList<Integer> y = this.dataArray;
XYSeries seriesY = new XYSeries("Y");
for (int i = 0; i < y.size(); i++) {
seriesY.add(i, y.get(i));
}
dataset = new XYMultipleSeriesDataset();
dataset.addSeries(seriesY);
renderer.setPanEnabled(true, false);
renderer.setClickEnabled(ClickEnabled);
renderer.setBackgroundColor(Color.WHITE);
renderer.setApplyBackgroundColor(true);
renderer.setChartTitle("Simple data");
renderer.setAxesColor(Color.BLACK);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setColor(Color.RED);
renderer.setPointStyle(PointStyle.DIAMOND);
mRenderer.addSeriesRenderer(renderer);
Intent intent = ChartFactory.getLineChartIntent(context, dataset, mRenderer, "Line Graph Title");
return intent;
}
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Counters_data");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
Integer objectValue = Integer.parseInt(object);
if (dataArray == null) {
dataArray = new ArrayList<Integer>();
dataArray.add(objectValue);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
}
And there is how I invoke charts:
public void lineGraphHandler(View view) {
LineGraph line = new LineGraph();
line.getData();
Intent lineIntent = line.getIntent(this);
startActivity(lineIntent);
}
And XML part:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/counters"
android:onClick="lineGraphHandler"
android:text="Charts"
android:id="#+id/charts"/>
There is my logcat:
03-26 08:42:13.096 1229-1229/com.example.tst D/dalvikvm﹕ Late-enabling
CheckJNI 03-26 08:42:13.487 1229-1229/com.example.tst D/libEGL﹕ loaded
/system/lib/egl/libEGL_genymotion.so 03-26 08:42:13.491
1229-1229/com.example.tst D/﹕ HostConnection::get() New Host
Connection established 0xb94f4270, tid 1229 03-26 08:42:13.551
1229-1229/com.example.tst D/libEGL﹕ loaded
/system/lib/egl/libGLESv1_CM_genymotion.so 03-26 08:42:13.551
1229-1229/com.example.tst D/libEGL﹕ loaded
/system/lib/egl/libGLESv2_genymotion.so 03-26 08:42:14.035
1229-1229/com.example.tst W/EGL_genymotion﹕ eglSurfaceAttrib not
implemented 03-26 08:42:14.039 1229-1229/com.example.tst
E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from GradienCache 03-26
08:42:14.043 1229-1229/com.example.tst E/OpenGLRenderer﹕
MAX_TEXTURE_SIZE: 4096 03-26 08:42:14.055 1229-1229/com.example.tst
E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from
Caches::initConstraints() 03-26 08:42:14.063 1229-1229/com.example.tst
E/OpenGLRenderer﹕ MAX_TEXTURE_SIZE: 4096 03-26 08:42:14.063
1229-1229/com.example.tst D/OpenGLRenderer﹕ Enabling debug mode 0
03-26 08:42:50.327 1229-1229/com.example.tst D/dalvikvm﹕ GC_FOR_ALLOC
freed 200K, 8% free 2975K/3228K, paused 10ms, total 13ms 03-26
08:42:51.675 1229-1229/com.example.tst D/dalvikvm﹕ GC_FOR_ALLOC freed
431K, 14% free 3056K/3540K, paused 22ms, total 28ms 03-26 08:42:52.043
1229-1229/com.example.tst W/EGL_genymotion﹕ eglSurfaceAttrib not
implemented 03-26 08:42:53.543 1229-1229/com.example.tst
I/Choreographer﹕ Skipped 89 frames! The application may be doing too
much work on its main thread. 03-26 08:43:01.747
1229-1229/com.example.tst D/AndroidRuntime﹕ Shutting down VM 03-26
08:43:01.747 1229-1229/com.example.tst W/dalvikvm﹕ threadid=1: thread
exiting with uncaught exception (group=0xa4d8fb20) 03-26 08:43:01.767
1229-1229/com.example.tst E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.tst, PID: 1229 java.lang.IllegalStateException:
Could not execute method of the activity at
android.view.View$1.onClick(View.java:3823) 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) Caused by:
java.lang.reflect.InvocationTargetException at
java.lang.reflect.Method.invokeNative(Native Method) at
java.lang.reflect.Method.invoke(Method.java:515) at
android.view.View$1.onClick(View.java:3818) 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) Caused by:
java.lang.NullPointerException at
com.example.tst.LineGraph.getIntent(LineGraph.java:36) at
com.example.tst.MainActivity.lineGraphHandler(MainActivity.java:44)
at java.lang.reflect.Method.invokeNative(Native Method) at
java.lang.reflect.Method.invoke(Method.java:515) at
android.view.View$1.onClick(View.java:3818) 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) 03-26 08:43:04.507
1229-1229/com.example.tst I/Process﹕ Sending signal. PID: 1229 SIG: 9
I don't understand where the problem is. My app starts but crashes immediately when I push "chart" button. Is it data type of problem or because I misunderstand something?
Thank you in advance.
I tried like this but still got crash:
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
Integer objectValue = Integer.parseInt(object);
if (dataArray == null) {
dataArray = new ArrayList<Integer>();
dataArray.add(objectValue);
ArrayList<Integer> y = dataArray;
XYSeries seriesY = new XYSeries("Y");
for (int i = 0; i < y.size(); i++) {
seriesY.add(i, y.get(i));
dataset = new XYMultipleSeriesDataset();
dataset.addSeries(seriesY);
}
}
Your getData() retrieves the data asynchronously. dataArray won't be initialized immediately when you call getIntent().
Wait for the async operation to complete before using the data there. For example, call the code requiring that data from the done() callback.

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.

FTP connection drivehq

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.

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