I am currently having trouble connecting to my webservice on android. I am using a Jetty web service and building it using ANT. On my laptop it works perfectly and displays items from my database. However it won't seem to connect on my Android application. Attached is the code and LOGCAT report.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class Android2Servlet extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dbtest);
TextView txtresp = (TextView)findViewById(R.id.servlet_response);
String url = "http://(MY LAPTOPS IP):8085/DB";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try{
System.out.println("About to execute");
HttpResponse response = client.execute(request);
String helpedResp=HttpUnpack.request(response);
System.out.println(helpedResp);
txtresp.setText(helpedResp);
System.out.println(response);
}catch(Exception ex){
txtresp.setText("Failed!");
ex.printStackTrace();
}
} }
The HTTP Unpack File
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
public class HttpUnpack {
public static String request(HttpResponse response){
String result = "";
try{ InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error retrieving response";
}
return result;
}
}
The HTTP Unpack and the Android2Servlet do not cause any errors, however the text box only returns "Failed!".
LOGCAT file
W/System.err(1282): android.os.NetworkOnMainThreadException
W/System.err(1282): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
W/System.err(1282): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
W/System.err(1282): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
W/System.err(1282): at libcore.io.IoBridge.connect(IoBridge.java:112)
W/System.err(1282): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
W/System.err(1282): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
W/System.err(1282): at java.net.Socket.connect(Socket.java:842)
W/System.err(1282): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
W/System.err(1282): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
W/System.err(1282): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
W/System.err(1282): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
W/System.err(1282): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
W/System.err(1282): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
W/System.err(1282): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
W/System.err(1282): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
W/System.err(1282): at myFood.myFood.Android2Servlet.onCreate(Android2Servlet.java:24)
W/System.err(1282): at android.app.Activity.performCreate(Activity.java:4465)
W/System.err(1282): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
W/System.err(1282): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
W/System.err(1282): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
W/System.err(1282): at android.app.ActivityThread.access$600(ActivityThread.java:123)
W/System.err(1282): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
W/System.err(1282): at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err(1282): at android.os.Looper.loop(Looper.java:137)
W/System.err(1282): at android.app.ActivityThread.main(ActivityThread.java:4424)
W/System.err(1282): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(1282): at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err(1282): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
W/System.err(1282): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
W/System.err(1282): at dalvik.system.NativeStart.main(Native Method)
Any response would be greatly helpful.
Regards.
EDIT:
I have now removed the network access and put it in another Java class. And called it form another class. And it is still returning the same errors. Any other advice?
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class androidconnectors {
public static final String main(String args[]) throws Exception {
String txtresp = "";
try{
String url = "http://(LAPTOPS IP):8085/Hello";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
System.out.println("About to execute");
HttpResponse response = client.execute(request);
String helpedResp=HttpUnpack.request(response); // Http Unpack is not part of
System.out.println(helpedResp); // of HttpClient library
txtresp =(helpedResp);
System.out.println(response);
}catch(Exception ex){
ex.printStackTrace();
}
return txtresp;
}
}
And the android class.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Settings extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dbtest);
Button mybutton = (Button) findViewById(R.id.buttonpress);
mybutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
TextView txtresp = (TextView)findViewById(R.id.servlet_response);
String[] args = null;
try {
String x = androidconnectors.main(args);
txtresp.setText(x);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtresp.setText("Failed");
}
}
});
}
}
It would seem, based on a quick google search, that since Honeycomb you are not supposed to execute network access on your app's main thread (to improve responsiveness).
Create another thread for network access as suggested here.
You can't do Network Operations on the UI Thread better use AsyncTask/Service/IntentService
NetworkOnMainThreadException
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.(Since API 11)
To resovled StrictMode issue you need to use below code in your activity -
static{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Related
i have a problem with a java code for Android. I will send a httpsRequest and i get back an JSON file. but i get a Error and i dont know why. I hope you can help me.
this is the LogCat what i get:
05-27 10:14:34.779: E/AndroidRuntime(24498): java.lang.RuntimeException: An error occured while executing doInBackground()
05-27 10:14:34.779: E/AndroidRuntime(24498): at android.os.AsyncTask$3.done(AsyncTask.java:300)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
05-27 10:14:34.779: E/AndroidRuntime(24498): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.lang.Thread.run(Thread.java:818)
05-27 10:14:34.779: E/AndroidRuntime(24498): Caused by: java.lang.IllegalArgumentException: HostnameVerifier is null
05-27 10:14:34.779: E/AndroidRuntime(24498): at javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(HttpsURLConnection.java:128)
05-27 10:14:34.779: E/AndroidRuntime(24498): at com.example.test.JSONTaskRegistrieren.doInBackground(JSONTaskRegistrieren.java:33)
05-27 10:14:34.779: E/AndroidRuntime(24498): at com.example.test.JSONTaskRegistrieren.doInBackground(JSONTaskRegistrieren.java:1)
05-27 10:14:34.779: E/AndroidRuntime(24498): at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-27 10:14:34.779: E/AndroidRuntime(24498): ... 4 more
My Code is
package com.example.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class JSONTaskRegistrieren extends AsyncTask<String, String, String>{
private static final HostnameVerifier HostnameVerifier = null;
#Override
protected String doInBackground(String...params){
String Servicepass;
String SecretToken;
BufferedReader reader = null;
URL url;
try{
url = new URL(params[0]);
HttpsURLConnection.setDefaultHostnameVerifier(HostnameVerifier);
new NullHostnameVerifier();
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("WWSVC-REQID", "1");
InputStream stream = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String output;
while ((output = reader.readLine()) != null){
buffer.append(output);
}
String finalJson = buffer.toString();
//System.out.println(buffer.toString());
JSONObject parentObject = new JSONObject(finalJson);
JSONObject servicepassobjekt = parentObject.getJSONObject("SERVICEPASS");
//System.out.println(servicepassobjekt.toString());
StringBuffer finalBufferedData = new StringBuffer();
JSONObject finalObject = servicepassobjekt;
Servicepass = finalObject.getString("PASSID");
SecretToken = finalObject.getString("APPID");
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
System.out.println(result);
}
}
and this is my Mainclass where i start the Request:
package com.example.test;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("unused")
public void onClick(View v) {
// ServiceURL
String ServiceURL = "https://192.168.0.64";
// Hersteller Hash
String HHash = "fa9b0dec3776ba123eba3049ec9f398h754";
// AppHash
String HAHash = "d20439ab3eabf9ebc3fae2c89b4869ai967";
// AppID
int AppID = 1;
new JSONTaskRegistrieren().execute(ServiceURL + "/WWSVC/WWSERVICE/REGISTER/"+HHash+"/"+HAHash+"/"+AppID+"/");
}});
}
}
Thank you very much for the help.
The piece to look for is the last Caused by: section of a stacktrace. In your case a IllegalArgumentException: HostnameVerifier is null which is caused by your code at com.example.test.JSONTaskRegistrieren.doInBackground(JSONTaskRegistrieren.java:33) (it's the first line mentioning your code)
From this you should find that the offending line of code is
HttpsURLConnection.setDefaultHostnameVerifier(HostnameVerifier);
and that the state of the HostnameVerifier variable at that point in time is null. When you check where assignments to that variable happen you see that the only time you assign something to it is at initialization time.
private static final HostnameVerifier HostnameVerifier = null;
Change that to
private static final HostnameVerifier HostnameVerifier = new NullHostnameVerifier();
and remove the line that did new NullHostnameVerifier();. It's creating a verifier and throws it away immediately since it's not stored in a variable.
HttpsURLConnection.setDefaultHostnameVerifier(HostnameVerifier);
HostnameVerifier argument sent here is null, as globally declared!
What is this statement for?
new NullHostnameVerifier();
Did you want to do HostnameVerfier = new NullHostnameVerifier();?
I think this variable is the cause
private static final HostnameVerifier HostnameVerifier = null;
you should use the following
url = new URL(params[0]);
HttpsURLConnection.setDefaultHostnameVerifier(url);
I am new to Android application development and Java programming, currently, I'm working on a project to retrieve from my database the status of a service. However, the application will stop working whenever I tried to submit my tracking ID.
MainActivity.java
package com.example.trackstatus;
import com.example.testapp.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button btnViewStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Buttons
btnViewStatus = (Button) findViewById(R.id.btnViewStatus);
// view products click event
btnViewStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching View status activity
Intent i = new Intent(getApplicationContext(), ViewTrackingStatusActivity.class);
startActivity(i);
}
});
}}
TrackStatus Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package = "com.example.trackstatus"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="20" />
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<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>
<!-- View Tracking Status Activity -->
<activity
android:name=".ViewTrackingStatusActivity"
android:label="View Tracking Status" >
</activity>
</application>
</manifest>
ViewTrackingStatusActivity.java
package com.example.trackstatus;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.testapp.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ViewTrackingStatusActivity extends Activity{
TextView textView1;
EditText trackingNumberText;
Button btnViewStatus;
String tid;
String tracking;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// url to get service status
private static String url = "http://10.0.2.2/1201716f/android%20connect/get_svc.php?tid=0";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_TRACKING = "tracking";
private static final String TAG_TID = "tid";
public String trackingno;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
trackingNumberText = (EditText) findViewById(R.id.trackingNumberText);
trackingno = trackingNumberText.getText().toString();
btnViewStatus = (Button) findViewById(R.id.btnViewStatus);
Intent intent = getIntent();
tid = intent.getStringExtra(TAG_TID);
// Getting tracking status details in background thread
new GetStatusDetails().execute();
//Toast.makeText(getApplicationContext(),"Hello",
// Toast.LENGTH_LONG).show();
}
class GetStatusDetails extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewTrackingStatusActivity.this);
pDialog.setMessage("Loading details");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tid", trackingno));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
// check your log for json response
Log.d("Tracking Status Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray trackingObj = json.getJSONArray(TAG_TRACKING); // JSON Array
// get first product object from JSON Array
JSONObject tracking = trackingObj.getJSONObject(0);
// display tracking status in ToastBox
Toast.makeText(ViewTrackingStatusActivity.this,json.getString(TAG_TRACKING),Toast.LENGTH_LONG).show();
}
else
{
//service with tid not found
Toast.makeText(getApplicationContext(),"Service not found!",Toast.LENGTH_LONG).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
return null;
}
}
}
JSONParser.java
package com.example.trackstatus;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}
else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
} 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;
}
}
Logcat
08-19 23:52:46.644: D/AndroidRuntime(3809): Shutting down VM
08-19 23:52:46.644: W/dalvikvm(3809): threadid=1: thread exiting with uncaught exception (group=0x41b37700)
08-19 23:52:46.654: E/AndroidRuntime(3809): FATAL EXCEPTION: main
08-19 23:52:46.654: E/AndroidRuntime(3809): android.os.NetworkOnMainThreadException
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
08-19 23:52:46.654: E/AndroidRuntime(3809): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
08-19 23:52:46.654: E/AndroidRuntime(3809): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
08-19 23:52:46.654: E/AndroidRuntime(3809): at libcore.io.IoBridge.connect(IoBridge.java:112)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.net.Socket.connect(Socket.java:842)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.example.trackstatus.JSONParser.makeHttpRequest(JSONParser.java:63)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.example.trackstatus.ViewTrackingStatusActivity$GetStatusDetails$1.run(ViewTrackingStatusActivity.java:92)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.Handler.handleCallback(Handler.java:730)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.Handler.dispatchMessage(Handler.java:92)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.Looper.loop(Looper.java:137)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.app.ActivityThread.main(ActivityThread.java:5293)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.lang.reflect.Method.invoke(Method.java:525)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
08-19 23:52:46.654: E/AndroidRuntime(3809): at dalvik.system.NativeStart.main(Native Method)
08-19 23:52:49.086: I/Process(3809): Sending signal. PID: 3809 SIG: 9
According to your LogCat message:
Caused by: java.lang.NullPointerException at com.example.trackstatus.ViewTrackingStatusActivity.onCreate(ViewTrackingStatusActivity.java:55)
You are missing :
setContentView(R.layout.your_layout);
where your EditText trackingNumberText must be declared.
thats the reason for what trackingNumberText is null
trackingNumberText = (EditText) findViewById(R.id.trackingNumberText);
More info:
setContentView() method
Update:
Since you have this new exception: NetworkOnMainThreadException
android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
you have to implement the use of AsyncTask
And hey! you donĀ“t need to use runOnUiThread inside the doInBackground() method of the Asynctask :P:
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
Move the lines that implies operations on UI thread like
Toast.makeText(getApplicationContext(),"Service not found!",Toast.LENGTH_LONG).show();
to the onPostExecute() method of the Asynctask
The error is in Line55
String trackingno = trackingNumberText.getText().toString();
trackingNumberText is NULL
instead try to do NULL check
String trackingno = "";
if(trackingNumberText.getText().length() > 0)
{
trackingno = trackingNumberText.getText().toString();
} else {
Toast.makeText(getApplicationContext(), "Enter values", Toast.LENGTH_LONG).show();
return;
}
EDIT:
You have to send all requests to server in Background Thread, use AsyncTask
Here is the detailed example for performing Network Operation.
i am the newbee in Android Development.
I had developed an app contains a login, the credentials must be passed in the text field and later it will call a webservice.
I am facing the issue as user and password is not getting copied at the required position.
Please help me out.
package com.authorwjf.http_get;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity implements OnClickListener {
EditText txtUserName;
EditText txtPassword;
#Override
public void onCreate(Bundle savedInstanceState) {
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String user= txtUserName.getText().toString();
String pass= txtPassword.getText().toString();
System.out.println("USERRRR"+user);
System.out.println(pass);
//String user="at#ril.com";
//String pass= "123456";
String accessTokenQry = "{"+
"\"uid\":\""+user+"\","+
"\"password\":\""+pass+"\","+
"\"consumptionDeviceId\":\"fder-et3w-3adw2-2erf\","+
"\"consumptionDeviceName\":\"Samsung Tab\""+
"}";
HttpPost httpPost = new HttpPost("http://devssg01.ril.com:8080/v2/dip/auth/login");
httpPost.setHeader("Content-Type",
"application/json");
httpPost.setHeader("X-API-Key",
"l7xx7914b8704b2d4b029ab9c4b1b9c66dbf");
StringEntity input;
try {
input = new StringEntity(accessTokenQry);
httpPost.setEntity(input);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String text = null;
try {
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
The LogCat Output is:
08-10 01:20:23.977: W/dalvikvm(760): threadid=14: thread exiting with uncaught exception (group=0x414c4700)
08-10 01:20:23.984: E/AndroidRuntime(760): FATAL EXCEPTION: AsyncTask #4
08-10 01:20:23.984: E/AndroidRuntime(760): java.lang.RuntimeException: An error occured while executing doInBackground()
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.lang.Thread.run(Thread.java:841)
08-10 01:20:23.984: E/AndroidRuntime(760): Caused by: java.lang.NullPointerException
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:66)
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:1)
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-10 01:20:23.984: E/AndroidRuntime(760): ... 3 more
You are trying to initialize EditTexts before layout loaded.
If you want to get EditText on layout, you must initialize it after layout loaded.
Here is correct code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
use this
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
I suggest following change in your code.
Just write following lines
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
above
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
Move the lines where you get the reference to text views after the setContentView function call:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
The fact is you need to call setContentView before initializing any widget in your layout because this is the call that "loads" your layout defined in layout_main.xml file into your activity.
Thanks a lot Guyz,
The issue is resolved now.
Special appreciation to JustWork
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
I have an android application project that connect to PHP server that I write it in codeigniter.
My JSONparser is:
package com.example.com.tourism;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
} 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;
}
}
and my activity java code that connect to the server is
package com.example.com.tourism;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class SignUp extends Activity {
EditText first,last,birth ,pass;
private ProgressDialog pDialog;
private static String url_create_user = "http://10.0.2.2/tourism/index.php/site/register";
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up);
Button signUp=(Button)findViewById(R.id.sign_up);
first =(EditText) findViewById(R.id.edfname);
last =(EditText) findViewById(R.id.edlname);
pass =(EditText) findViewById(R.id.edpass);
signUp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Createnewuser().execute();
}
});
}
class Createnewuser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignUp.this);
pDialog.setMessage("Creating User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = first.getText().toString();
String price = last.getText().toString();
String description = pass.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("first_name", name));
params.add(new BasicNameValuePair("last_name", price));
params.add(new BasicNameValuePair("password", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_user,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
and the error in log cat is
07-07 11:30:44.159: E/JSON Parser(20514): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
07-07 11:30:44.189: W/dalvikvm(20514): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
07-07 11:30:44.229: E/AndroidRuntime(20514): FATAL EXCEPTION: AsyncTask #1
07-07 11:30:44.229: E/AndroidRuntime(20514): java.lang.RuntimeException: An error occured while executing doInBackground()
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.lang.Thread.run(Thread.java:856)
07-07 11:30:44.229: E/AndroidRuntime(20514): Caused by: java.lang.NullPointerException
07-07 11:30:44.229: E/AndroidRuntime(20514): at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:98)
07-07 11:30:44.229: E/AndroidRuntime(20514): at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:1)
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-07 11:30:44.229: E/AndroidRuntime(20514): ... 4 more
07-07 11:30:44.429: I/Choreographer(20514): Skipped 49 frames! The application may be doing too much work on its main thread.
07-07 11:30:44.779: I/Choreographer(20514): Skipped 222 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.069: I/Choreographer(20514): Skipped 149 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.369: I/Choreographer(20514): Skipped 194 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.459: I/Choreographer(20514): Skipped 50 frames! The application may be doing too much work on its main thread.
07-07 11:30:46.019: E/WindowManager(20514): Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here
07-07 11:30:46.019: E/WindowManager(20514): android.view.WindowLeaked: Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here
07-07 11:30:46.019: E/WindowManager(20514): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
07-07 11:30:46.019: E/WindowManager(20514): at android.app.Dialog.show(Dialog.java:281)
07-07 11:30:46.019: E/WindowManager(20514): at com.example.com.tourism.SignUp$Createnewuser.onPreExecute(SignUp.java:75)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.AsyncTask.execute(AsyncTask.java:534)
07-07 11:30:46.019: E/WindowManager(20514): at com.example.com.tourism.SignUp$1.onClick(SignUp.java:57)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.View.performClick(View.java:4204)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.View$PerformClick.run(View.java:17355)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Handler.handleCallback(Handler.java:725)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Handler.dispatchMessage(Handler.java:92)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Looper.loop(Looper.java:137)
07-07 11:30:46.019: E/WindowManager(20514): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-07 11:30:46.019: E/WindowManager(20514): at java.lang.reflect.Method.invokeNative(Native Method)
07-07 11:30:46.019: E/WindowManager(20514): at java.lang.reflect.Method.invoke(Method.java:511)
07-07 11:30:46.019: E/WindowManager(20514): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-07 11:30:46.019: E/WindowManager(20514): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-07 11:30:46.019: E/WindowManager(20514): at dalvik.system.NativeStart.main(Native Method)
i don't know where the problem is, please help me
is my code incorrect ???
if any one have correct code please give it to me i am using codeigniter for php and this is the code that i call it above
function register_get()
{
$json = array('status' => false );
if($this->input->post()==null){
$this -> response($json, 200);
}
$firstname = $this->post("first_name");
$lastname = $this->post("last_name");
$password = $this->post("password");
if(!$firstname || !$lastname || !$password){
$json['status'] = "wrong insert";
$this -> response($json, 200);
}
$this->load->model('Data_model');
$result = $this->Data_model->search($firstname, $lastname);
if($result)
{
$this->Data_model->insert($firstname,$lastname,$password);
$json['status'] = true;
}
// here if false..
$this -> response($json, 200);
}
There are issues with your PHP. You are not passing back any JSON. You will need to change your script to encode your array into JSON.
$result = json_encode($json)
Returning the actual JSON will help. Make sure you are not returning any HTML either. Your Java is trying to parse a JSON response, but you are responding with <!DOCTYPE...
Hello i am trying to load images from a server into a gallery but always keep giving me this error:
04-28 00:54:47.596: W/dalvikvm(715): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-28 00:54:47.608: E/AndroidRuntime(715): FATAL EXCEPTION: main
04-28 00:54:47.608: E/AndroidRuntime(715): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.plateamobile/com.plateamobile.ProdDetails}: java.lang.NullPointerException
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.os.Looper.loop(Looper.java:123)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-28 00:54:47.608: E/AndroidRuntime(715): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 00:54:47.608: E/AndroidRuntime(715): at java.lang.reflect.Method.invoke(Method.java:521)
04-28 00:54:47.608: E/AndroidRuntime(715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-28 00:54:47.608: E/AndroidRuntime(715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-28 00:54:47.608: E/AndroidRuntime(715): at dalvik.system.NativeStart.main(Native Method)
04-28 00:54:47.608: E/AndroidRuntime(715): Caused by: java.lang.NullPointerException
04-28 00:54:47.608: E/AndroidRuntime(715): at com.plateamobile.ProdDetails.set_info(ProdDetails.java:138)
04-28 00:54:47.608: E/AndroidRuntime(715): at com.plateamobile.ProdDetails.onCreate(ProdDetails.java:49)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-28 00:54:47.608: E/AndroidRuntime(715): ... 11 more
This is my code:
package com.plateamobile;
import java.io.BufferedInputStream;
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 java.util.List;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.Gallery.LayoutParams;
public class ProdDetails extends Activity {
private ImageSwitcher mSwitcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prod_details);
Bundle extras = getIntent().getExtras();
((TextView)findViewById(R.id.prod_name)).setText(extras.getString("name"));
((TextView)findViewById(R.id.price_prod)).setText(new general().formatNumb(extras.getString("price")));
set_info();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.prod_details, menu);
return true;
}
public void set_info(){
ObjConexion object = new ObjConexion();
SoapObject request = new SoapObject(object.NameSpace(), "getProdinfo");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
Bundle extras = getIntent().getExtras();
PropertyInfo idPro =new PropertyInfo();
idPro.setName("id");
idPro.setValue(extras.getString("id"));
idPro.setType(String.class);
request.addProperty(idPro);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(object.Url());
androidHttpTransport.debug = true;
try {
androidHttpTransport.call("getProdinfo", envelope);
List<SoapPrimitive> response = (List<SoapPrimitive>) envelope.getResponse();
((TextView)findViewById(R.id.commerce)).setText(response.get(0).toString());
((TextView)findViewById(R.id.description)).setContentDescription(response.get(1).toString());
}catch (Exception e) {
e.printStackTrace();
Toast.makeText(this,e.getMessage().toString(),Toast.LENGTH_LONG).show();
}
request = new SoapObject(object.NameSpace(), "getProdImg");
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
idPro =new PropertyInfo();
idPro.setName("id");
idPro.setValue(extras.getString("id"));
idPro.setType(Integer.class);
request.addProperty(idPro);
envelope.setOutputSoapObject(request);
androidHttpTransport = new HttpTransportSE(object.Url());
androidHttpTransport.debug = true;
ArrayList<SoapObject> imagesList = new ArrayList<SoapObject>();
try {
androidHttpTransport.call("getProdImg", envelope);
List<SoapObject> response = (List<SoapObject>) envelope.getResponse();
for (int cont=0; cont<response.size() ;cont++){
SoapObject responseChild = (SoapObject) response.get(cont);
imagesList.add(responseChild);
}
}catch (Exception e) {
e.printStackTrace();
if (e.getMessage() == null){
Toast.makeText(this,"Error en la conexion",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,e.getMessage().toString(),Toast.LENGTH_LONG).show();
}
}
Gallery _gallery_ = (Gallery) findViewById(R.id.images_prod);
if (imagesList!=null){
_gallery_.setAdapter(new ImageAdapter(getApplicationContext(), imagesList));
}else{
Log.e("DEBUGTAG", "Remtoe Image Exception");
}
}
public void goBack(View v){
Intent intent = new Intent(ProdDetails.this, main_win.class);
startActivity(intent);
}
public class ImageAdapter extends BaseAdapter {
/** The parent context */
private Context myContext;
/** URL-Strings to some remote images. */
private ArrayList<SoapObject> pckg_data;
/** Simple Constructor saving the 'parent' context. */
public ImageAdapter(Context c, ArrayList<SoapObject> data) {
this.myContext = c;
this.pckg_data = data;
}
/** Returns the amount of images we have defined. */
public int getCount() { return this.pckg_data.size(); }
/* Use the array-Positions as unique IDs */
public Object getItem(int position) { return position; }
public long getItemId(int position) { return position; }
/** Returns a new ImageView to
* be displayed, depending on
* the position passed. */
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(this.myContext);
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(pckg_data.get(position).getPropertyAsString(1));
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
/* Apply the Bitmap to the ImageView that will be returned. */
i.setImageBitmap(bm);
} catch (IOException e) {
Log.e("DEBUGTAG", "Remtoe Image Exception", e);
}
/* Image should be scaled as width/height are set. */
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
/* Set the Width/Height of the ImageView. */
i.setLayoutParams(new Gallery.LayoutParams(150, 150));
return i;
}
/** Returns the size (0.0f to 1.0f) of the views
* depending on the 'offset' to the center. */
public float getScale(boolean focused, int offset) {
/* Formula: 1 / (2 ^ offset) */
return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
}
}
}
The first time your app is created there is no intent calling it. So Bundle extras = getIntent().getExtras(); causes the NullPointerException.
Enclose the statement in a try block.
try
{
Bundle extras = getIntent().getExtras();
}
catch(Exception E){
//do nothing
}
But this isn't the right way to do it.
If this activity is going to be called again, I suggest you use onNewIntent() method and make this activity singleTop.
http://developer.android.com/reference/android/app/Activity.html
http://developer.android.com/guide/topics/manifest/activity-element.html