RSS Unexpected Token, reading in xml file [duplicate] - java

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.

Related

App just forcecloses and stops working, why?

I'm a newbie android developer and I am making, or trying to make a File explorer that wil be capable of opening almost all file types. From music files, through video files, document files and many others. BUT, I came across a huge problem that my app compiled successfully but it does not open. Here is my code:
package com.tstudios.openit;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
private String root;
private TextView myPath;
private ImageView mImageView=(ImageView) findViewById(R.id.gallery);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myPath = (TextView)findViewById(R.id.path);
root = Environment.getExternalStorageDirectory().getPath();
getDir(root);
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
String filename = f.getName();
String filenameArray[] = filename.split("\\.");
String extension = filenameArray[filenameArray.length-1];
TextView row=(TextView)findViewById(R.id.rowtext);
//if(extension=="jpg"){
//mImageView.setImageBitmap(BitmapFactory.decodeFile(dirPath));
//}
//if(extension!=null){
//row.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_launcher,0,0,0);
//}
Arrays.sort(files, filecomparator);
for(int i=0; i < files.length; i++)
{
File file = files[i];
if(!file.isHidden() && file.canRead()){
path.add(file.getPath());
if(file.isDirectory()){
item.add(file.getName() + "/");
}else{
item.add(file.getName());
}
}
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
Comparator<? super File> filecomparator = new Comparator<File>(){
public int compare(File file1, File file2) {
if(file1.isDirectory()){
if (file2.isDirectory()){
return String.valueOf(file1.getName().toLowerCase()).compareTo(file2.getName().toLowerCase());
}else{
return -1;
}
}else {
if (file2.isDirectory()){
return 1;
}else{
return String.valueOf(file1.getName().toLowerCase()).compareTo(file2.getName().toLowerCase());
}
}
}
};
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
File file = new File(path.get(position));
String filename = file.getName();
String filenameArray[] = filename.split("\\.");
String extension = filenameArray[filenameArray.length-1];
if (file.isDirectory())
{
if(extension=="jpg"){
mImageView.setImageBitmap(BitmapFactory.decodeFile(filename));
getDir(path.get(position));
}else{
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK", null).show();
}
}else {
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK", null).show();
}
}
}
and this is logcat I get when I lauch the app, btw I am using Sony Xperia Z1 Compact if that helps
08-28 12:10:54.779 4169-4169/com.tstudios.openit D/AndroidRuntime﹕ Shutting down VM
08-28 12:10:54.779 4169-4169/com.tstudios.openit W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4164cd88)
08-28 12:10:54.789 4169-4169/com.tstudios.openit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tstudios.openit, PID: 4169
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.tstudios.openit/com.tstudios.openit.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at com.tstudios.openit.MainActivity.<init>(MainActivity.java:25)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2154)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:212)
            at android.app.ActivityThread.main(ActivityThread.java:5135)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
         at dalvik.system.NativeStart.main(Native Method)
And another question, how to put icons before file names ? Depending on extension
Thank you very much for your help
Move the
mImageView=(ImageView) findViewById(R.id.gallery);
to onCreate() after setContentView(), leaving just the member variable declaration at the class level:
private ImageView mImageView;
Before onCreate() there's no window yet for the activity and you'll get the NPE.
Before setContentView() there's no view hierarchy to search from and a null is returned.
private ImageView mImageView=(ImageView) findViewById(R.id.gallery);
to use findViewById you need a valid Activity. It happens after the activity has been attached
Place this line private ImageView mImageView=(ImageView) findViewById(R.id.gallery); after setContentView . It will resolve null pointer exception. After this, if you get any other exception, Pls tell.

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.

Android Json HttpGet/Post HttpResponse

I am trying to take a product from mysql database according to its barcode number. I checked my php codes they are working but on android side i am taking an error.
Here my GetProductDetails class (i think this part is ok);
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 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.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Query_product extends Activity {
EditText txtId, txtName, txtPrice, txtDesc;
Button btnSave, btnDelete;
String ID = "";
String pid;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// url to get all products list
private static final String url_product_details = "http://10.0.2.2/ssa/get_product_details.php";
private static final String url_update_product = "http://10.0.2.2/ssa/update_product.php";
private static final String url_delete_product = "http://10.0.2.2/ssa/delete_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "barcode";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.query_prod);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
ID += " " + getIntent().getExtras().getString(Constants.ID);
pid = ID;
new GetProductDetails().execute();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveProductDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new DeleteProduct().execute();
}
});
}
class GetProductDetails extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Query_product.this);
pDialog.setMessage("Loading product details. Please wait...");
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(TAG_PID, pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_details, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtId = (EditText) findViewById(R.id.inputId);
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtId.setText(product.getString(TAG_PID));
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
}
else
{
String error = "Not found!";
Toast.makeText(Query_product.this, error, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
Here makeHttpRequest class;
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;
}
}
I couldn't be able to solve the problem. Program runs until this line;
HttpResponse httpResponse = httpClient.execute(httpGet);
Logcat errors;
12-14 18:05:30.994: E/AndroidRuntime(986): FATAL EXCEPTION: main
12-14 18:05:30.994: E/AndroidRuntime(986): android.os.NetworkOnMainThreadException
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
12-14 18:05:30.994: E/AndroidRuntime(986): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
12-14 18:05:30.994: E/AndroidRuntime(986): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-14 18:05:30.994: E/AndroidRuntime(986): at libcore.io.IoBridge.connect(IoBridge.java:112)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.net.Socket.connect(Socket.java:842)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.example.ssa.JSONParser.makeHttpRequest(JSONParser.java:66)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.example.ssa.Query_product$GetProductDetails$1.run(Query_product.java:134)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.Handler.handleCallback(Handler.java:725)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.Handler.dispatchMessage(Handler.java:92)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.Looper.loop(Looper.java:137)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.app.ActivityThread.main(ActivityThread.java:5041)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.lang.reflect.Method.invoke(Method.java:511)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-14 18:05:30.994: E/AndroidRuntime(986): at dalvik.system.NativeStart.main(Native Method)
12-14 18:10:31.483: I/Process(986): Sending signal. PID: 986 SIG: 9
12-14 18:10:33.372: D/gralloc_goldfish(1025): Emulator without GPU emulation detected.
You cannot perform network tasks on the main thread because it might block your application in case the network task takes a very long time. You need to run such tasks in the background using AsyncTask instead.
Here's the documentation.
Try using the below code inside your main activity below setContentView(), to avoid the networkOnmainThread exception..
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Looks like the error is not of json.
You are trying to call a url from Main Thread which is not allowed from android 4.0
Try using AsynTask or call the url from secondary thread.

XML parsing failure

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.

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