XML parsing failure - java

I am writing an application for XML parser in android But when I download the code and run it, it runs perfectly ,
But I wrote the same code but not working, Why so?
Is there any prerequisite for that? Please help me with this
I am getting an error in XMLParser.java
package com.xmlparser;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
My Log Cat
11-22 15:35:53.675: E/AndroidRuntime(19208): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xmlparser/com.xmlparser.Xparser}: android.os.NetworkOnMainThreadException
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.app.ActivityThread.access$600(ActivityThread.java:140)
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.os.Handler.dispatchMessage(Handler.java:99)
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.os.Looper.loop(Looper.java:137)
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.app.ActivityThread.main(ActivityThread.java:4898)
11-22 15:35:53.675: E/AndroidRuntime(19208): at java.lang.reflect.Method.invokeNative(Native Method)
11-22 15:35:53.675: E/AndroidRuntime(19208): at java.lang.reflect.Method.invoke(Method.java:511)
11-22 15:35:53.675: E/AndroidRuntime(19208): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
11-22 15:35:53.675: E/AndroidRuntime(19208): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
11-22 15:35:53.675: E/AndroidRuntime(19208): at dalvik.system.NativeStart.main(Native Method)
11-22 15:35:53.675: E/AndroidRuntime(19208): Caused by: android.os.NetworkOnMainThreadException
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
11-22 15:19:21.500: E/AndroidRuntime(16631): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-22 15:19:21.500: E/AndroidRuntime(16631): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-22 15:19:21.500: E/AndroidRuntime(16631): at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-22 15:19:21.500: E/AndroidRuntime(16631): at com.xmlparser.XMLParser.getXmlFromUrl(XMLParser.java:45)
11-22 15:19:21.500: E/AndroidRuntime(16631): at com.xmlparser.Xparser.onCreate(Xparser.java:37)
11-22 15:19:21.500: E/AndroidRuntime(16631): at android.app.Activity.performCreate(Activity.java:5206)
11-22 15:19:21.500: E/AndroidRuntime(16631): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
11-22 15:19:21.500: E/AndroidRuntime(16631): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
this is my Xparser.java
package com.xmlparser;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class Xparser extends ListActivity {
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML key nodes
static final String KEY_ITEM = "item";
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xmlparser);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL);// getting XML
Document doc = parser.getDomElement(xml);// getting Dom Element
NodeList n1 = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for(int i=0 ; i < n1.getLength(); i++){
HashMap<String,String> map = new HashMap<String,String>();
Element e = (Element) n1.item(i);
//adding each child to Hashmap node key
map.put(KEY_ID, parser.getValue(e,KEY_ID));
map.put(KEY_NAME, parser.getValue(e,KEY_NAME));
map.put(KEY_COST, "Rs."+ parser.getValue(e,KEY_COST));
map.put(KEY_DESC, parser.getValue(e,KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_select_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String desc = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
Intent in = new Intent();
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_DESC, desc);
in.putExtra(KEY_COST, cost);
startActivity(in);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.xmlparser, menu);
return true;
}
}

The exception tells you everything you need to know. You are trying to submit data on the main thread. Do the networking operations in a separate thread.
There's a link in the docs that explains it, and this might help you to move on.

Related

RSS Unexpected Token, reading in xml file [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm trying to create a RSS Reader that reads in a Rss feed and displays it in a list view. I got his to work with other RSS Feeds but I can't get it to work on the Feed that I actually need it for. I validated the feed and it says that it is a valid RSS feed with no errors. I know that the problem/solution is in the getDomFromXMLString method which is where it is actually pulling the XML in, but I can't figure out how to make it read it is correctly.
Here's my Main Activity
package com.example.lehi.events;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
String key_items = "item";
String key_title = "title";
String key_description = "description";
String key_link = "link";
String key_date = "pubDate";
ListView lstPost = null;
List<HashMap<String, Object>> post_lists = new ArrayList<HashMap<String, Object>>();
List<String> lists = new ArrayList<String>();
ArrayAdapter<String> adapter = null;
RSSReader rssfeed = new RSSReader();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstPost = (ListView) findViewById(R.id.lstPosts);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_2, android.R.id.text1, lists) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView txt1 = (TextView) view
.findViewById(android.R.id.text1);
TextView txt2 = (TextView) view
.findViewById(android.R.id.text2);
HashMap<String, Object> data = post_lists.get(position);
txt1.setText(data.get(key_title).toString());
txt2.setText(data.get(key_description).toString());
return view;
}
};
Document xmlFeed;
xmlFeed = rssfeed.getRSSFromServer("http://calendar.byui.edu/RSSFeeds.aspx?data=hhAbVFpDFO7OxcTcYlM9Lk3inbX%2bJ%2baS3fubTE468TQI91kccS33vQ%3d%3d");
NodeList nodes = xmlFeed.getElementsByTagName("item");
for (int i = 0; i < nodes.getLength(); i++) {
Element item = (Element) nodes.item(i);
HashMap<String, Object> feed = new HashMap<String, Object>();
feed.put(key_title, rssfeed.getValue(item, key_title));
feed.put(key_description, rssfeed.getValue(item, key_description));
feed.put(key_link, rssfeed.getValue(item, key_link));
feed.put(key_date, rssfeed.getValue(item, key_date));
post_lists.add(feed);
lists.add(feed.get(key_title).toString());
}
lstPost.setAdapter(adapter);
}
}
Here's the feed URL
http://calendar.byui.edu/RSSFeeds.aspx?data=hhAbVFpDFO7OxcTcYlM9Lk3inbX%2bJ%2baS3fubTE468TQI91kccS33vQ%3d%3d
Thanks
Edit:
Here's the object that rssfeed is being declared as.
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.os.StrictMode;
public class RSSReader {
DefaultHttpClient httpClient = new DefaultHttpClient();
public Document getRSSFromServer(String url) {
Document response = null;
response = getDomFromXMLString(getFeedFromServer(url));
return response;
}
private String getFeedFromServer(String url) {
String xml = null;
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try {
HttpGet httpget =new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
return xml;
}
private Document getDomFromXMLString(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (Exception e) {
}
return doc;
}
public String getValue(Element item, String key) {
NodeList nodeList = item.getElementsByTagName(key);
return this.getElementValue(nodeList.item(0));
}
public final String getElementValue(Node node) {
Node child;
if (node != null) {
if (node.hasChildNodes()) {
for (child = node.getFirstChild(); child != null; child = child
.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
}
It's the org.xml.sax.SAXParseException: Unexpected token (position:TEXT #1:4 in java.io.StringReader#19916b6d) that I am trying to figure out.
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ org.xml.sax.SAXParseException: Unexpected token (position:TEXT #1:4 in java.io.StringReader#19916b6d)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at org.apache.harmony.xml.parsers.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:146)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at com.example.lehi.events.RSSReader.getDomFromXMLString(RSSReader.java:58)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at com.example.lehi.events.RSSReader.getRSSFromServer(RSSReader.java:29)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at com.example.lehi.events.MainActivity.onCreate(MainActivity.java:56)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at android.app.Activity.performCreate(Activity.java:5933)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at android.app.ActivityThread.access$800(ActivityThread.java:144)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5221)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
03-15 18:29:08.307 3612-3612/com.example.lehi.events W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
03-15 18:29:08.308 3612-3612/com.example.lehi.events W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-15 18:29:08.308 3612-3612/com.example.lehi.events W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Try printing the stack trace if there's an exception in getDomFromXMLString. I'd guess there is an exception, which is currently being swallowed, and the returned Document is then null.
Edit: Now we see the SAXParseException: Unexpected token . That is the UTF-8 byte order mark. Try EntityUtils.toString(httpEntity, "UTF-8") and see if that helps it to swallow the BOM.

Android Application Force closing (retrieving data)

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.

java.lang.NullPointerException xml parsing

this code should parse the xml and show it ! but it has exeption :
02-02 12:36:49.508: I/Choreographer(1184): Skipped 32 frames! The application may be doing too much work on its main thread.
02-02 12:36:50.926: W/System.err(1184): java.lang.NullPointerException
02-02 12:36:50.926: W/System.err(1184): at com.example.sample.itcuties.android.reader.ITCutiesReaderAppActivity.onCreate(ITCutiesReaderAppActivity.java:52)
02-02 12:36:50.946: W/System.err(1184): at android.app.Activity.performCreate(Activity.java:5008)
02-02 12:36:50.946: W/System.err(1184): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
02-02 12:36:50.946: W/System.err(1184): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
02-02 12:36:50.966: W/System.err(1184): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
02-02 12:36:50.966: W/System.err(1184): at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-02 12:36:50.986: W/System.err(1184): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
02-02 12:36:50.986: W/System.err(1184): at android.os.Handler.dispatchMessage(Handler.java:99)
02-02 12:36:50.998: W/System.err(1184): at android.os.Looper.loop(Looper.java:137)
02-02 12:36:51.006: W/System.err(1184): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-02 12:36:51.018: W/System.err(1184): at java.lang.reflect.Method.invokeNative(Native Method)
02-02 12:36:51.026: W/System.err(1184): at java.lang.reflect.Method.invoke(Method.java:511)
02-02 12:36:51.026: W/System.err(1184): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-02 12:36:51.036: W/System.err(1184): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-02 12:36:51.036: W/System.err(1184): at dalvik.system.NativeStart.main(Native Method)
02-02 12:36:51.046: I/System.out(1184): xml activity Excpetion = java.lang.NullPointerException
02-02 12:36:51.736: I/Choreographer(1184): Skipped 39 frames! The application may be doing too much work on its main thread.
02-02 12:36:53.596: D/dalvikvm(1184): GC_CONCURRENT freed 180K, 4% free 8234K/8519K, paused 96ms+114ms, total 356ms
I cant find the reason!!!!
package com.example.sample.itcuties.android.reader;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Main application activity.
*
* #author ITCuties
*
*/
public class ITCutiesReaderAppActivity extends Activity {
NodeList nodeList;
/**
* This method creates main application view
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set view
try{
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
LongOperation lOp = new LongOperation(this);
lOp.execute("");
if(nodeList.getLength() > 0)
{
name = new TextView[nodeList.getLength()];
website = new TextView[nodeList.getLength()];
category = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
name[i] = new TextView(this);
website[i] = new TextView(this);
category[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
name[i].setText("Name = " + ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("website");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
website[i].setText("Website = " + ((Node) websiteList.item(0)).getNodeValue());
category[i].setText("Website Category = " + websiteElement.getAttribute("category"));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
}
/** Set the layout view to display */
setContentView(layout);
} catch (Exception e) {
System.out.println("xml activity Excpetion = " + e);
}
}
private class LongOperation extends AsyncTask<String, Void, String> {
Context LongOperation;
public LongOperation(Context context){
this.LongOperation = context;
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("item");
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
LongOperation lOp = new LongOperation(this); lOp.execute("");
From this line, it seems you are filling nodeList in an AsyncTask, but instead of waiting for it to be filled, you start parsing it immediately. Make sure to start parsing from onPostExecuted in your LongOperation.
BTW, it would not be a bad idea to also do the parsing in the background.

Java NullPointer loading remote image to android gallery with imageadapter

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

Having trouble connecting to webservice through android

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

Categories