Here is my log cat. Unfortunately I am not a pro in reading errors from logcat so please help me :)
05-30 12:12:16.510: I/System.out(838): We made it this far 1
05-30 12:12:17.230: I/System.out(838): We made it this far 2
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to resolve exception class 748 (Lcom/fasterxml/jackson/core/JsonParseException;)
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to find exception handler at addr 0x2a
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejecting opcode 0x0d at 0x002a
05-30 12:12:17.250: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.250: W/dalvikvm(838): Verifier rejected class Lcom/example/bitmapdisplay/MainActivity$URLArray;
05-30 12:12:17.250: D/AndroidRuntime(838): Shutting down VM
05-30 12:12:17.250: W/dalvikvm(838): threadid=1: thread exiting with uncaught exception (group=0xb1adaba8)
05-30 12:12:17.270: E/AndroidRuntime(838): FATAL EXCEPTION: main
05-30 12:12:17.270: E/AndroidRuntime(838): Process: com.example.bitmapdisplay, PID: 838
05-30 12:12:17.270: E/AndroidRuntime(838): java.lang.VerifyError: com/example/bitmapdisplay/MainActivity$URLArray
05-30 12:12:17.270: E/AndroidRuntime(838): at com.example.bitmapdisplay.MainActivity.onCreate(MainActivity.java:72)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.Activity.performCreate(Activity.java:5231)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.os.Handler.dispatchMessage(Handler.java:102)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.os.Looper.loop(Looper.java:136)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-30 12:12:17.270: E/AndroidRuntime(838): at java.lang.reflect.Method.invokeNative(Native Method)
05-30 12:12:17.270: E/AndroidRuntime(838): at java.lang.reflect.Method.invoke(Method.java:515)
05-30 12:12:17.270: E/AndroidRuntime(838): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-30 12:12:17.270: E/AndroidRuntime(838): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-30 12:12:17.270: E/AndroidRuntime(838): at dalvik.system.NativeStart.main(Native Method)
05-30 12:12:30.390: I/Process(838): Sending signal. PID: 838 SIG: 9
Here is the logcat code and here is my Java code. It seems like the problems are coming from the thread URLArray because, as seen in the logcat, the system doesn't even print the third "we made it this far":
package com.example.bitmapdisplay;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.fasterxml.jackson.core.JsonParseException;
import android.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class MainActivity extends Activity {
/**
* Bitmap items na dimage displaying
*/
Bitmap image;
BitmapDrawable bd;
ImageView temp;
ProgressDialog pd;
/**
* JSON URL
*/
URL url;
/**
* Data from JSON file
*/
ArrayList<String> urls;
ArrayList<ImageView> images;
JsonParsing obj;
String json_link_str = "http://api.tumblr.com/v2/blog/humansofnewyork.com/posts?api_key=7ag2CJXOuxuW3vlVS5wQG6pYA6a2ZQcSCjzZsAp2pDbVwf3xEk¬es_info=true&filter=text";
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println(" We made it this far 1");
super.onCreate(savedInstanceState);
setContentView(com.example.bitmapdisplay.R.layout.image_container);
counter = 0;
images = new ArrayList<ImageView>();
urls = new ArrayList<String>();
System.out.println(" We made it this far 2");
new URLArray().execute();
}
/**
* Fills the ListView
*/
private void fillGridView() {
ArrayAdapter<ImageView> adapter = new ArrayAdapter<ImageView>(this, com.example.bitmapdisplay.R.layout.image_container,images);
GridView grid = (GridView) findViewById(com.example.bitmapdisplay.R.id.gvImages);
grid.setAdapter(adapter);
}
public class URLArray extends AsyncTask<Void, Void, Void > {
public URLArray() {
}
#Override
protected Void doInBackground(Void...params ) {
try {
System.out.println(" We made it this far 3");
URL json_link = new URL(json_link_str);
JsonParsing parse_images = new JsonParsing(json_link);
try {
parse_images.parseFile(3, urls);
System.out.println(" We made it this far 4");
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
obj = parse_images;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void arg) {
super.onPreExecute();
System.out.println(" We made it this far 5");
urls = obj.getURLs();
new TheTask().execute();
}
}
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
System.out.println(" We made it this far 6");
pd = new ProgressDialog(MainActivity .this);
pd.show();
System.out.println(" We made it this far 7");
try
{
int counter = 0;
for (ImageView temp : images) {
image = downloadBitmap(urls.get(counter));
temp.setImageBitmap(image);
images.add(temp);
counter++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
System.out.println(" We made it this far 8");
super.onPostExecute(result);
pd.dismiss();
if(image!=null)
{
fillGridView();
}
}
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
//forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
image = BitmapFactory.decodeStream(inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + e.toString());
}
return image;
}
}
The key problem is here
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to resolve exception class 748 (Lcom/fasterxml/jackson/core/JsonParseException;)
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to find exception handler at addr 0x2a
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejecting opcode 0x0d at 0x002a
05-30 12:12:17.250: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.250: W/dalvikvm(838): Verifier rejected class Lcom/example/bitmapdisplay/MainActivity$URLArray;
and it all goes downhill from there.
Looks like JsonParseException (and possibly other classes from Jackson) are not being included in your APK. This could happen if they're not being exported by Eclipse.
Instead of adding it as an external library, just place jackson-core-x.x.x.jar in the libs folder of your Android project and it should be enough to ensure this.
Related
I have been stuck for weeks.....for this problem
I am using AsynTask to send data to php and recieve a name to print
but it showed this error anyone to help ??
12-29 19:34:12.623: D/dalvikvm(799): GC_CONCURRENT freed 188K, 11% free 2629K/2948K, paused 25ms+61ms, total 218ms
12-29 19:34:13.282: D/gralloc_goldfish(799): Emulator without GPU emulation detected.
12-29 19:34:42.132: W/System.err(799): java.lang.NullPointerException
12-29 19:34:42.164: W/System.err(799): at android.app.Activity.findViewById(Activity.java:1839)
12-29 19:34:42.164: W/System.err(799): at com.example.myweb.MainActivity.afterEffect(MainActivity.java:64)
12-29 19:34:42.164: W/System.err(799): at com.example.myweb.toPHP.onPreExecute(toPHP.java:47)
12-29 19:34:42.164: W/System.err(799): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
12-29 19:34:42.164: W/System.err(799): at android.os.AsyncTask.execute(AsyncTask.java:534)
12-29 19:34:42.164: W/System.err(799): at com.example.myweb.MainActivity$1.onClick(MainActivity.java:54)
12-29 19:34:42.172: W/System.err(799): at android.view.View.performClick(View.java:4204)
12-29 19:34:42.172: W/System.err(799): at android.view.View$PerformClick.run(View.java:17355)
12-29 19:34:42.172: W/System.err(799): at android.os.Handler.handleCallback(Handler.java:725)
12-29 19:34:42.185: W/System.err(799): at android.os.Handler.dispatchMessage(Handler.java:92)
12-29 19:34:42.185: W/System.err(799): at android.os.Looper.loop(Looper.java:137)
12-29 19:34:42.192: W/System.err(799): at android.app.ActivityThread.main(ActivityThread.java:5041)
12-29 19:34:42.212: W/System.err(799): at java.lang.reflect.Method.invokeNative(Native Method)
12-29 19:34:42.212: W/System.err(799): at java.lang.reflect.Method.invoke(Method.java:511)
12-29 19:34:42.212: W/System.err(799): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-29 19:34:42.222: W/System.err(799): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-29 19:34:42.222: W/System.err(799): at dalvik.system.NativeStart.main(Native Method)
JSONParser.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
toPHP.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class toPHP extends AsyncTask {
MainActivity main = new MainActivity();
private JSONParser jsonParser;
String email,password;
EditText emailBox;
EditText passwordBox;
#Override
protected void onPreExecute() {
super.onPreExecute();
main.afterEffect("sending...");
emailBox = (EditText) main.findViewById(R.id.email);
passwordBox = (EditText) main.findViewById(R.id.password);
email = emailBox.getText().toString();
password = passwordBox.getText().toString();
}
protected JSONObject doInBackground(String... args) {
toPHP userFunction = new toPHP();
JSONObject json = null;
try {
json = userFunction.getUserLoggedIn(email, password);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
public JSONObject getUserLoggedIn(String email,String password) throws ClientProtocolException, IOException, JSONException{
JSONObject json = null;
/*
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost/testand.php");
*/
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("email", email));
pairs.add(new BasicNameValuePair("password", password));
//post.setEntity(new UrlEncodedFormEntity(pairs));
//HttpResponse response = client.execute(post);
//HttpEntity resEntity = response.getEntity();
//if (resEntity != null) {
//String responseStr = EntityUtils.toString(resEntity).trim();
json = jsonParser.getJSONFromUrl("http://localhost/testand.php", pairs);
//}
return json;
}
protected void onPostExecute(JSONObject json) throws JSONException {
String myName = json.getString("name");
String str = myName + ", Welcome to Socionet. :) ";
main.afterEffect(str);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
return null;
}
}
MainActivity.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
Button button;
EditText emailBox;
EditText passwordBox;
String emailId;
String passwordId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.login1);
emailBox = (EditText)findViewById(R.id.email);
passwordBox = (EditText)findViewById(R.id.password);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
new toPHP().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void afterEffect(String str){
TextView textV1 = (TextView)findViewById(R.id.textV1);
textV1.setText(str);
}
}
UPDATE 1
new errors after #hasan83 's fixes
12-29 21:38:27.588: W/dalvikvm(1283): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
12-29 21:38:27.748: E/AndroidRuntime(1283): FATAL EXCEPTION: AsyncTask #1
12-29 21:38:27.748: E/AndroidRuntime(1283): java.lang.RuntimeException: An error occured while executing doInBackground()
12-29 21:38:27.748: E/AndroidRuntime(1283): at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
12-29 21:38:27.748: E/AndroidRuntime(1283): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.lang.Thread.run(Thread.java:856)
12-29 21:38:27.748: E/AndroidRuntime(1283): Caused by: java.lang.NullPointerException
12-29 21:38:27.748: E/AndroidRuntime(1283): at com.example.myweb.toPHP.getUserLoggedIn(toPHP.java:99)
12-29 21:38:27.748: E/AndroidRuntime(1283): at com.example.myweb.toPHP.doInBackground(toPHP.java:67)
12-29 21:38:27.748: E/AndroidRuntime(1283): at com.example.myweb.toPHP.doInBackground(toPHP.java:1)
12-29 21:38:27.748: E/AndroidRuntime(1283): at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-29 21:38:27.748: E/AndroidRuntime(1283): ... 4 more
You can't create a new MainActivity in your AsyncTask. When you are in your MainActivity, pass the activity to the constructor of the AsyncTask. You will be able to get and update your views in the onPreExecute() method.
public class toPHP extends AsyncTask {
public toPHP(Activity activity) {
}
}
And in your activity:
new toPHP(MainActivity.this).execute();
Add a constructor so that you can pass in the current MainActivity to your AsyncTask
public class toPHP extends AsyncTask {
final MainActivity main;
public toPHP(MainActivity main) {
this.main = main;
}
...
then call like so
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
new toPHP(MainActivity.this).execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Error says it's unable to find your TextView with id of R.id.textV1. Make sure it's available in the content view :R.layout.activity_main
But the main problem is why are you doing this MainActivity main = new MainActivity(), in your AsyncTask. It should be passed by reference from the actual Activity.
Points:
I don't see #Override keyword before onPostExecute and doInBackground methods.
Move the code in onPreExecute to doInBackground.
Send the main activity as a parameter for the AsynkTask execute method.
Catch the activity on the do doInBackground.
dont' declare an object of toPhp just call getUserLoggedIn. you are in the same class.
That's it.
new toPHP().execute(MainActivity.this);
#Override
protected Object doInBackground(Object... args) {
main = (MainActivity) args[0];
main.afterEffect("sending...");
emailBox = (EditText) main.findViewById(R.id.email);
passwordBox = (EditText) main.findViewById(R.id.password);
email = emailBox.getText().toString();
password = passwordBox.getText().toString();
..
}
can anyone help me?
I'm new to android and currently trying to built an android chat application.
However I have this issue that I am currently facing.
I am using Openfire as my server and while trying to connect to openfire, this error pops up and crashes the application when I clicked the button to login.
This is my LoginActivity.java
package com.example.chattp;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private EditText accountEditText;
private EditText passwordEditText;
protected Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
accountEditText = (EditText) findViewById(R.id.login_account);
passwordEditText = (EditText) findViewById(R.id.login_password);
findViewById(R.id.login_login).setOnClickListener(new OnClickListener(){
public void onClick(View v){
String account = accountEditText.getText().toString();
String password = passwordEditText.getText().toString();
if(account.equals("") || password.equals(""))
{
Toast.makeText(LoginActivity.this, "Username and Password must be entered", Toast.LENGTH_SHORT).show();
}else
{
ClientConServer ccs = new ClientConServer (LoginActivity.this);
boolean b = ccs.login(account, password);
//if successful login
if(b)
{
Toast.makeText(LoginActivity.this, "Login is Successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, TestActivity.class));
}else{
Toast.makeText(LoginActivity.this, "Login is unsuccessful", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public class ClientConServer {
private static final String HOST = "192.168.1.4";
private static final int PORT = 5222;
private Context context;
public ClientConServer(Context context){
this.context = context;
}
public boolean login(String a, String p){
ConnectionConfiguration config = new ConnectionConfiguration(HOST, PORT);
config.setSASLAuthenticationEnabled(false);
XMPPConnection connection = new XMPPConnection(config);
try{
connection.connect();
connection.login(a, p);
return true;
} catch(XMPPException e){
e.printStackTrace();
}
return false;
}
}
Errors shown on Logcat
01-14 23:35:35.500: E/dalvikvm(2533): Could not find class 'org.jivesoftware.smack.ConnectionConfiguration', referenced from method com.example.chattp.LoginActivity$ClientConServer.login
01-14 23:35:35.500: W/dalvikvm(2533): VFY: unable to resolve new-instance 823 (Lorg/jivesoftware/smack/ConnectionConfiguration;) in Lcom/example/chattp/LoginActivity$ClientConServer;
01-14 23:35:35.510: D/dalvikvm(2533): VFY: replacing opcode 0x22 at 0x0001
01-14 23:35:35.510: D/dalvikvm(2533): DexOpt: unable to opt direct call 0x14d5 at 0x07 in Lcom/example/chattp/LoginActivity$ClientConServer;.login
01-14 23:35:35.580: D/dalvikvm(2533): DexOpt: unable to opt direct call 0x14d7 at 0x0f in Lcom/example/chattp/LoginActivity$ClientConServer;.login
01-14 23:35:35.590: D/AndroidRuntime(2533): Shutting down VM
01-14 23:35:35.590: W/dalvikvm(2533): threadid=1: thread exiting with uncaught exception (group=0xb0eb8648)
01-14 23:35:35.610: E/AndroidRuntime(2533): FATAL EXCEPTION: main
01-14 23:35:35.610: E/AndroidRuntime(2533): java.lang.NoClassDefFoundError: org.jivesoftware.smack.ConnectionConfiguration
01-14 23:35:35.610: E/AndroidRuntime(2533): at com.example.chattp.LoginActivity$ClientConServer.login(LoginActivity.java:70)
01-14 23:35:35.610: E/AndroidRuntime(2533): at com.example.chattp.LoginActivity$1.onClick(LoginActivity.java:45)
01-14 23:35:35.610: E/AndroidRuntime(2533): at android.view.View.performClick(View.java:4240)
01-14 23:35:35.610: E/AndroidRuntime(2533): at android.view.View$PerformClick.run(View.java:17721)
01-14 23:35:35.610: E/AndroidRuntime(2533): at android.os.Handler.handleCallback(Handler.java:730)
01-14 23:35:35.610: E/AndroidRuntime(2533): at android.os.Handler.dispatchMessage(Handler.java:92)
01-14 23:35:35.610: E/AndroidRuntime(2533): at android.os.Looper.loop(Looper.java:137)
01-14 23:35:35.610: E/AndroidRuntime(2533): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-14 23:35:35.610: E/AndroidRuntime(2533): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 23:35:35.610: E/AndroidRuntime(2533): at java.lang.reflect.Method.invoke(Method.java:525)
01-14 23:35:35.610: E/AndroidRuntime(2533): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-14 23:35:35.610: E/AndroidRuntime(2533): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-14 23:35:35.610: E/AndroidRuntime(2533): at dalvik.system.NativeStart.main(Native Method)
Usually these java.lang.NoClassDefFoundError: org.jivesoftware.smack.ConnectionConfiguration type of errors will come when the app is not recoginzed the jar files . in this case it's smack.jar .
Even I faced this issue i have selected the smack.jar in project- > properties - > Order and Export and make sure to include in Libraries.And do clean and re-build the project .Sometimes restart of eclipse also works.
public class Connection
{
public final static String SERVER_HOST = "192.168.88.158";
public final static int SERVER_PORT = 5222;
public final static String SERVICE_NAME = "192.168.88.158";
public final static String LOGIN = "manish";
public final static String PASSWORD = "android";
private Context context;
static XMPPConnection m_connection;
static Presence presence;
public static ArrayList<HashMap<String, String>> usersList;
public static ConnectionConfiguration config = new ConnectionConfiguration(
SERVER_HOST, SERVER_PORT, SERVICE_NAME);
public Connection(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
public static void initConnection() throws XMPPException {
// Initialization de la connexion
m_connection = new XMPPConnection(config);
m_connection.connect();
//Create user
AccountManager newAccount = new AccountManager(m_connection);
m_connection = new XMPPConnection(config);
m_connection.connect();
newAccount.createAccount("Rahul", "android");
presence = new Presence(Presence.Type.available);
m_connection.sendPacket(presence); }}
public boolean login(String username, String Password){
m_connection = new XMPPConnection(config);
config.setSASLAuthenticationEnabled(false);
XMPPConnection connection = new XMPPConnection(config); `enter code here`
try{
connection.connect();
connection.login(username, Password);
return true;`enter code here`
} catch(XMPPException e){`enter code here`
e.printStackTrace();
}
return false; }}
for establishing a connection it's really help's you .
And any query related to registry user in openfire server always welcome.
Thanks
I have problem whit getting my project to work i will
paste the java files and error log hopefully someone can give me a hint.
The app crash when button R.id.bskickaTidSc3 in TidSc3.java is clicked.
error log
06-08 12:45:49.365: E/dalvikvm(1243): Could not find class 'org.apache.poi.hssf.usermodel.HSSFWorkbook', referenced from method com.example.spapp_beta.TidsedelExcel.SetExcelVecka
06-08 12:45:49.365: W/dalvikvm(1243): VFY: unable to resolve new-instance 67 (Lorg/apache/poi/hssf/usermodel/HSSFWorkbook;) in Lcom/example/spapp_beta/TidsedelExcel;
06-08 12:45:49.365: D/dalvikvm(1243): VFY: replacing opcode 0x22 at 0x0000
06-08 12:45:49.365: D/dalvikvm(1243): DexOpt: unable to opt direct call 0x0087 at 0x09 in Lcom/example/spapp_beta/TidsedelExcel;.SetExcelVecka
06-08 12:45:49.375: D/AndroidRuntime(1243): Shutting down VM
06-08 12:45:49.375: W/dalvikvm(1243): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-08 12:45:49.387: E/AndroidRuntime(1243): FATAL EXCEPTION: main
06-08 12:45:49.387: E/AndroidRuntime(1243): java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.example.spapp_beta.TidsedelExcel.SetExcelVecka(TidsedelExcel.java:17)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.example.spapp_beta.TidSc3.onClick(TidSc3.java:96)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.view.View.performClick(View.java:4204)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.view.View$PerformClick.run(View.java:17355)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Handler.handleCallback(Handler.java:725)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Handler.dispatchMessage(Handler.java:92)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Looper.loop(Looper.java:137)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-08 12:45:49.387: E/AndroidRuntime(1243): at java.lang.reflect.Method.invokeNative(Native Method)
06-08 12:45:49.387: E/AndroidRuntime(1243): at java.lang.reflect.Method.invoke(Method.java:511)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-08 12:45:49.387: E/AndroidRuntime(1243): at dalvik.system.NativeStart.main(Native Method)
06-08 12:46:37.675: E/Trace(1261): error opening trace file: No such file or directory (2)
06-08 12:46:38.065: D/gralloc_goldfish(1261): Emulator without GPU emulation detected.
TidSc3.java
package com.example.spapp_beta;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TidSc3 extends Activity implements OnClickListener {
Button skicka, visa;
TextView namn, vecka, ar, arbplts, man,tis,ons,tors,fre,lor,son,oI,oII,restid,km,trakt;
EditText v,ovrigt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tid_sc3);
ovrigt = (EditText) findViewById(R.id.eTovrigt);
v = (EditText) findViewById(R.id.eTtidSc3vecka);
namn = (TextView) findViewById(R.id.tVsamNamn);
vecka = (TextView) findViewById(R.id.tVsamVecka);
ar = (TextView) findViewById(R.id.tVsamAr);
arbplts = (TextView) findViewById(R.id.tVsamArbplts);
man = (TextView) findViewById(R.id.tVsamMan);
tis = (TextView) findViewById(R.id.tVsamTis);
ons = (TextView) findViewById(R.id.tVsamOns);
tors = (TextView) findViewById(R.id.tVsamTors);
fre = (TextView) findViewById(R.id.tVsamFre);
lor = (TextView) findViewById(R.id.tVsamLor);
son = (TextView) findViewById(R.id.tVsamSon);
oI = (TextView) findViewById(R.id.tVsamOI);
oII = (TextView) findViewById(R.id.tVsamOII);
restid = (TextView) findViewById(R.id.tVsamRestid);
km = (TextView) findViewById(R.id.tVsamKm);
trakt = (TextView) findViewById(R.id.tVsamTrakt);
visa = (Button) findViewById(R.id.bvisa);
skicka = (Button) findViewById(R.id.bskickaTidSc3);
skicka.setOnClickListener(this);
visa.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()){
case R.id.bvisa:
String s = v.getText().toString();
long l = Long.parseLong(s);
String[] veckaA = new String[16];
DbTidsedel2013 get = new DbTidsedel2013(TidSc3.this);
get.open();
veckaA = get.VeckaArray(l);
get.close();
vecka.setText(veckaA[0]);
ar.setText(veckaA[1]);
namn.setText(veckaA[2]);
arbplts.setText(veckaA[3] + "\n");
man.setText(veckaA[4]);
tis.setText(veckaA[5]);
ons.setText(veckaA[6]);
tors.setText(veckaA[7]);
fre.setText(veckaA[8]);
lor.setText(veckaA[9]);
son.setText(veckaA[10]);
restid.setText(veckaA[11]);
km.setText(veckaA[12]);
oI.setText(veckaA[13]);
oII.setText(veckaA[14]);
trakt.setText(veckaA[15]);
break;
case R.id.bskickaTidSc3:
String s1 = v.getText().toString();
long l1 = Long.parseLong(s1);
String[] veckaA1 = new String[16];
DbTidsedel2013 get1 = new DbTidsedel2013(TidSc3.this);
get1.open();
veckaA1 = get1.VeckaArray(l1);
get1.close();
TidsedelExcel tidEx = new TidsedelExcel();
try {
tidEx.SetExcelVecka(veckaA1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String ov = ovrigt.getText().toString();
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Tid vecka " + veckaA1[0]);
intent.putExtra(Intent.EXTRA_TEXT, ov);
intent.setData(Uri.parse("mailto:"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tid_sc3, menu);
return true;
}
}
TidsedelExcel.java
package com.example.spapp_beta;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class TidsedelExcel {
public void SetExcelVecka (String[] vecka) throws FileNotFoundException, IOException{
Workbook workbook = new HSSFWorkbook(new FileInputStream("/assets/TsO.xls"));
Sheet sheet = workbook.getSheetAt(0);
Cell cellvecka1 = sheet.getRow(1).getCell(14);
cellvecka1.setCellValue(vecka[0]);
Cell cellvecka2 = sheet.getRow(7).getCell(0);
cellvecka2.setCellValue(vecka[0]);
Cell cellAr = sheet.getRow(1).getCell(10);
cellAr.setCellValue(vecka[1]);
Cell cellNamn = sheet.getRow(3).getCell(0);
cellNamn.setCellValue(vecka[2]);
Cell cellArbplts = sheet.getRow(3).getCell(10);
cellArbplts.setCellValue(vecka[3]);
Cell cellMan = sheet.getRow(7).getCell(3);
int man = Integer.parseInt(vecka[4]);
cellMan.setCellValue(man);
Cell cellTis = sheet.getRow(7).getCell(4);
int tis = Integer.parseInt(vecka[5]);
cellTis.setCellValue(tis);
Cell cellOns = sheet.getRow(7).getCell(5);
int ons = Integer.parseInt(vecka[6]);
cellOns.setCellValue(ons);
Cell cellTors = sheet.getRow(7).getCell(6);
int tors = Integer.parseInt(vecka[7]);
cellTors.setCellValue(tors);
Cell cellFre = sheet.getRow(7).getCell(7);
int fre = Integer.parseInt(vecka[8]);
cellFre.setCellValue(fre);
Cell cellLor = sheet.getRow(7).getCell(8);
int lor = Integer.parseInt(vecka[9]);
cellLor.setCellValue(lor);
Cell cellSon = sheet.getRow(7).getCell(9);
int son = Integer.parseInt(vecka[10]);
cellSon.setCellValue(son);
Cell cellRestid = sheet.getRow(7).getCell(10);
int restid = Integer.parseInt(vecka[11]);
cellRestid.setCellValue(restid);
Cell cellMil = sheet.getRow(7).getCell(16);
int mil = Integer.parseInt(vecka[12]);
cellMil.setCellValue(mil);
Cell cellOI = sheet.getRow(7).getCell(13);
int oI = Integer.parseInt(vecka[13]);
cellOI.setCellValue(oI);
Cell cellOII = sheet.getRow(7).getCell(14);
int oII = Integer.parseInt(vecka[14]);
cellOII.setCellValue(oII);
Cell cellTrakt = sheet.getRow(7).getCell(15);
int trakt = Integer.parseInt(vecka[15]);
cellTrakt.setCellValue(trakt);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("/assets/Tidsedel_V_" + vecka[0] + "_" + vecka[1] + ".xls");
workbook.write(fileOut);
fileOut.close();
}
}
Thanks to anyone that is kind to help out
The error says
06-08 12:45:49.387: E/AndroidRuntime(1243): java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
Go to Project properties > Java Build Path > Order and Export tab and select the library you have used in your project..
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 am trying to send a string from a android application to a servlet and then retrieve that string to my android application ,but when i try to invoke the servlet it force close on me
and i dont know why (im very new to android and this is a practice exercise for me)
here is my android simple app:
ANDROID
package com.theopentutorials.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpGetServletActivity extends Activity implements OnClickListener {
Button button;
TextView outputText;
public static String request = "kjo ishte e gjitha";
public static final String URL = ("http://10.0.2.2:8080/HttpGetServlet/HelloWorldServlet?param1=" + request);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}
}
and here is my simple servlet
SERVLET
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String par1 = request.getParameter("param1");
PrintWriter out = response.getWriter();
out.println(par1);
}
}
And the logcat log error says
01-10 13:36:50.014: E/AndroidRuntime(1187): FATAL EXCEPTION: AsyncTask #1
01-10 13:36:50.014: E/AndroidRuntime(1187): java.lang.RuntimeException: An error occured while executing doInBackground()
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.lang.Thread.run(Thread.java:856)
01-10 13:36:50.014: E/AndroidRuntime(1187): Caused by: java.lang.NullPointerException: lock == null
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.Reader.<init>(Reader.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.InputStreamReader.<init>(InputStreamReader.java:122)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.InputStreamReader.<init>(InputStreamReader.java:59)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.getOutputFromUrl(HttpGetServletActivity.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:54)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:1)
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-10 13:36:50.014: E/AndroidRuntime(1187): ... 4 more
doest somebody have any idea ?
Thank you for your help in advance !
Have a nice day!
You need to add the internet access permission
<uses-permission android:name="android.permission.INTERNET"/>
I found that you should use the URLEncoder to encode the url because your url contains spaces. Please check http://developer.android.com/reference/java/net/URLEncoder.html
You have forgot to set param1 from your android app.
connection.setRequestProperty("param1", "Your String Value");
then you will get the value back as response from Servlet.