Hi I'm still learning android on my free time, I'm trying to collect data from a MySQL DB on android using Json, but I have a problem handling the threads.
any hint to point on the right direction on this problem? maybe to know where the error is?
I'm relatively new to android
the JsonParser comes as following
package com.remotedata.firstapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JsonParser {
static InputStream is = null;
static JSONObject json_data = null;
static String result = "";
// constructor
public JsonParser() {
}
public JSONObject getJSONFromUrl(ArrayList<NameValuePair> nameValuePairs, String url) {
//http post this will keep the same way as it was (it's important to do not forget to add Internet access to androidmanifest.xml
InputStream is = null;
String result ="";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response that we receive from the php file into a String()
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
// try parse the string to a Json object
try {
json_data = new JSONObject(result);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return Json String
return json_data;
}
}
the ListActivity is the following:
package com.remotedata.firstapp;
import java.util.ArrayList;
import java.util.HashMap;
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.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
public class DataconectActivity extends ListActivity {
// adding strings that are going to be the tags of the nodes for the list view in the ListAdapter
private static String TAG_PRODID = "codigo";
private static final String TAG_NOMBRE = "nombre";
private static final String TAG_DESCRIPCION = "descripcion";
private static final String TAG_COLOR = "color";
private static final String TAG_PESO = "peso";
private static final String TAG_PRECIO = "precio";
private static final String TAG_DISPONIBILIDAD = "disponibilidad";
private static final String TAG_INFO = "resultados";
// remember to change the url to try it with the web server http://trialsols.webege.com/mobil.php after this is important to add at least 10.000 items to the db to ensure the query efficiency
private static final String url ="http://192.168.1.50/mobilv1.php";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> jsonResultList = new ArrayList<HashMap<String, String>>();
//the price data to send must change in the application so it will be bundle with a text box
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("precio","10"));
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
JSONObject json_data = jParser.getJSONFromUrl(nameValuePairs, url);
JSONArray jArray = null;
try {
// Getting Array of JsonData
jArray = json_data.getJSONArray(TAG_INFO);
// looping through All JsonData
for(int i = 0; i < jArray.length(); i++){
JSONObject c = jArray.getJSONObject(i);
String nombre = c.getString("nombre");
String prodid = c.getString("prodid");
String descripcion = c.getString("descripcion");
String color = c.getString("color");
String peso = c.getString("peso");
String precio = c.getString("precio");
String disponibilidad = c.getString("disponibilidad");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PRODID, prodid);
map.put(TAG_NOMBRE, nombre);
map.put(TAG_DESCRIPCION, descripcion);
map.put(TAG_COLOR, color);
map.put(TAG_PESO, peso);
map.put(TAG_PRECIO, precio);
map.put(TAG_DISPONIBILIDAD, disponibilidad);
// adding HashList to ArrayList
jsonResultList.add(map);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
//adding the results of the parsed JSON data to a listView using a ListAdapter
ListAdapter adapter = new SimpleAdapter(this, jsonResultList,
R.layout.datalistitems,
new String[] { TAG_NOMBRE, TAG_PRECIO, TAG_DISPONIBILIDAD }, new int[] {
R.id.dbnombretxt, R.id.dbpreciotxt, R.id.dbdisponibilidadtxt });
// add in a ListActivity We need to make a parser with thissetListAdapter(adapter);
setListAdapter(adapter);
}
}
also the stacktrace is:
02-22 15:12:56.122: I/jdwp(338): received file descriptor 10 from ADB
02-22 15:12:56.162: D/ddm-heap(338): Got feature list request
02-22 15:12:56.353: D/AndroidRuntime(338): Shutting down VM
02-22 15:12:56.353: W/dalvikvm(338): threadid=3: thread exiting with uncaught exception (group=0x4001aa28)
02-22 15:12:56.353: E/AndroidRuntime(338): Uncaught handler: thread main exiting due to uncaught exception
02-22 15:12:56.373: E/AndroidRuntime(338): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.remotedata.firstapp/com.remotedata.firstapp.DataconectActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
02-22 15:12:56.373: E/AndroidRuntime(338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2401)
02-22 15:12:56.373: E/AndroidRuntime(338): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
02-22 15:12:56.373: E/AndroidRuntime(338): at android.app.ActivityThread.access$2100(ActivityThread.java:116)
02-22 15:12:56.373: E/AndroidRuntime(338): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
02-22 15:12:56.373: E/AndroidRuntime(338): at android.os.Handler.dispatchMessage(Handler.java:99)
02-22 15:12:56.373: E/AndroidRuntime(338): at android.os.Looper.loop(Looper.java:123)
02-22 15:12:56.373: E/AndroidRuntime(338): at android.app.ActivityThread.main(ActivityThread.java:4203)
02-22 15:12:56.373: E/AndroidRuntime(338): at java.lang.reflect.Method.invokeNative(Native Method)
02-22 15:12:56.373: E/AndroidRuntime(338): at java.lang.reflect.Method.invoke(Method.java:521)
02-22 15:12:56.373: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
02-22 15:12:56.373: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
02-22 15:12:56.373: E/AndroidRuntime(338): at dalvik.system.NativeStart.main(Native Method)
02-22 15:12:56.373: E/AndroidRuntime(338): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
02-22 15:12:56.373: E/AndroidRuntime(338): at android.app.ListActivity.onContentChanged(ListActivity.java:236)
02-22 15:12:56.373: E/AndroidRuntime(338): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:316)
02-22 15:12:56.373: E/AndroidRuntime(338): at android.app.Activity.setContentView(Activity.java:1620)
02-22 15:12:56.373: E/AndroidRuntime(338): at com.remotedata.firstapp.DataconectActivity.onCreate(DataconectActivity.java:36)
02-22 15:12:56.373: E/AndroidRuntime(338): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
02-22 15:12:56.373: E/AndroidRuntime(338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
02-22 15:12:56.373: E/AndroidRuntime(338): ... 11 more
02-22 15:12:56.384: I/dalvikvm(338): threadid=7: reacting to signal 3
02-22 15:12:56.384: E/dalvikvm(338): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
At line 36 of my activity I have:
super.onCreate(savedInstanceState);
also in Main.xml I have this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Datos de la tabla Productos" />
<ListView
android:smoothScrollbar="true"
android:id="#+id/datalst"
android:focusableInTouchMode="true"
android:layout_width="fill_parent"
android:layout_height="50dp"/>
</LinearLayout>
The AndroidManifest.xml have the following permissions
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
If you extends ListActivity to your Activity ,Your Main.xml must have Listview whose id is like
android:id="#android:id/list" ,So change it First....
The problem is that your DataconectActivity extends the ListActivity type, while you are seting as its contentView a LinearLayout (as seen at main.xml).
You can find more information on List views and Activities at http://developer.android.com/resources/tutorials/views/hello-listview.html
So, a solution is that you DataconectActivity extends the Activity class, so it can show in an LinearLayout view (defined in main.xml).
Other solution, is just get rid of the line 36 of your code, and let the ListActivity load the ListView as default.
Related
I have the following code.
I want to post on the first time the user press a button that the data will be send to httpclient and will return data. This works fine (Button 1). When a user press button 1 it will give the right results.
Then I want to post a second time with different data to the httpclient. When a user press button 2. The data will be send to the function but the logs (see code) returns in the exceptions every time NULL. So I think it will not send to httpclient and will not fill the httppost with the data I want to send.
My question is, what do I wrong or do I forget?
Do I need to create a second httpclient handler?
Do I need to create a second httppost handler?
Please help.
Thank you.
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import info.androidhive.customlistviewvolley.util.MyHttpClient;
public class Login extends Activity {
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ProgressDialog offlineDialog = null;
String logged, token, valid;
String expired = "expired";
String status, responseContent = "0";
String msg = "";
public void onCreate(Bundle savedInstanceState) {
httpclient=new MyHttpClient(getApplicationContext());
httppost= new HttpPost("https://www.test.com/json/index.php");
b = (Button)findViewById(R.id.buttonLogin);
c = (Button)findViewById(R.id.shareData);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(Login.this, "","Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
String username = 'abc';
String password = 'xxx';
String token = '12321abcksadkm';
c.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
offlineDialog = ProgressDialog.show(Login.this, "", "Share content...", true);
new Thread(new Runnable() {
public void run() {
// This will be executed but will give NULL and offcourse no results
share.connectDP(username,password,"share","18228",token);
}
}).start();
}
});
}
void login(){
try{
final byte[] SALT;
Random random = new Random();
random.setSeed(System.currentTimeMillis());
byte[] buf = new byte[20];
random.nextBytes(buf);
SALT = buf;
nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("token",SALT.toString().trim()));
Log.i("Salt", "Key =" + SALT.toString().trim());
Log.i("test", "test" + nameValuePairs);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
String responseContent = EntityUtils.toString(response.getEntity());
//Log.d("Response", responseContent );
JSONObject jsonObject = new JSONObject(responseContent);
JSONArray jArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject json_data = jArray.getJSONObject(i);
logged = json_data.getString("status"); // obtain status
token = json_data.getString("token"); // obtain token
valid = json_data.getString("valid"); // obtain validation period
expired = "no";
Log.i("Logged JSON", "Result?" + json_data.getString("status"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void connectDP(String username, String password, String action, String id, String token){
// This is passed, it returns the data = :)
Log.i("connect", "username" + username);
Log.i("connect", "password" + password);
Log.i("connect", "action" + action);
Log.i("connect", "id" + id);
Log.i("connect", "token" + token);
try{
final byte[] SALT;
Random random = new Random();
random.setSeed(System.currentTimeMillis());
byte[] buf = new byte[20];
random.nextBytes(buf);
SALT = buf;
nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username",username.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",password.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("token",SALT.toString().trim()));
Log.i("Salt", "Key =" + SALT.toString().trim());
Log.i("test", "test" + nameValuePairs);
//// <!---- After here it will break, but no any error or warning -----!>
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
String responseContent = EntityUtils.toString(response.getEntity());
//Log.d("Response", responseContent );
JSONObject jsonObject = new JSONObject(responseContent);
JSONArray jArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject json_data = jArray.getJSONObject(i);
logged = json_data.getString("status"); // obtain status
token = json_data.getString("token"); // obtain token
valid = json_data.getString("valid"); // obtain validation period
expired = "no";
Log.i("Logged JSON", "Result?" + json_data.getString("status"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
}
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ usernameabc
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ passwordxxx
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ actionshare
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ id18228
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ token12321abcksadkm
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/test 1﹕ test[username=abc, password=xxx, requestAction=share, requestFile=18228, load_remote_token=12321abcksadkm
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 1a﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 2﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 2a﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 3﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 4﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 4a﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 5﹕ 0
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/System.out﹕ Exception : Value 0 of type java.lang.Integer cannot be converted to JSONObject
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/Log share﹕ [ 04-03 19:33:25.390 169:0x204 W/InputManagerService ]
Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#4156a2c8
package info.androidhive.customlistviewvolley.util;
import android.content.Context;
import info.androidhive.customlistviewvolley.R;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import java.io.InputStream;
import java.security.KeyStore;
import org.apache.http.conn.ssl.SSLSocketFactory;
public class MyHttpClient extends DefaultHttpClient {
final Context _context;
public MyHttpClient(Context context) {
this._context = context;
}
#Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// Register for port 443 our SSLSocketFactory with our keystore
// to the ConnectionManager
registry.register(new Scheme("https", (org.apache.http.conn.scheme.SocketFactory) newSslSocketFactory(), 443));
return new SingleClientConnManager(getParams(), registry);
}
private SSLSocketFactory newSslSocketFactory() {
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("BKS");
// Get the raw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
InputStream in = _context.getResources().openRawResource(R.raw.keystore);
try {
// Initialize the keystore with the provided trusted certificates
// Also provide the password of the keystore
trusted.load(in, "xxxxxxxx".toCharArray());
} finally {
in.close();
}
// Pass the keystore to the SSLSocketFactory. The factory is responsible
// for the verification of the server certificate.
SSLSocketFactory sf = new SSLSocketFactory(trusted);
// Hostname verification from certificate
// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ java.lang.NullPointerException
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at info.androidhive.customlistviewvolley.Login.connectDP(Login.java:247)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at info.androidhive.customlistviewvolley.adater.CustomGridOfflineMedia$2.onClick(CustomGridOfflineMedia.java:200)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.view.View.performClick(View.java:3511)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.view.View$PerformClick.run(View.java:14110)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:605)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:92)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4424)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
i hope somebody more qualified will answer your question soon, until then something to maybe look into:
HttpPost.reset inherited from AbstractExecutionAwareRequest
says in the docs:
"Resets internal state of the request making it reusable."
making me think that maybe if you do not reset the httppost object it isn't reusable...
src: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/methods/AbstractExecutionAwareRequest.html#reset()
According to the logcat, your API doesnt response a valid JSON format.
It must be "response" : "0" or something liek that instead of plain 0.
I suggest you to check the server side code for connectDB function and what it returns.
This has been solved by changing some code.
I have followed a tutorial which shows you how you can connect to an rss feed, and pull down the data into a listView. The problem is, is that I want to be able to loop through multiple feeds adding them to the same listView, but when I try to do this....it brings back the following logCat error.
If anyone can help me, that would be great thanks!
Code:
package com.androidhive.xmlparsing;
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.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 AndroidXMLParsingActivity extends ListActivity {
// All static variables
//static final String URL = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
String[] URL = new String[2];
int count = 0;
// XML node keys
static final String KEY_ITEM = "item"; // parent node
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
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rssRun();
}
public void rssRun()
{
URL[0] = "http://www.skysports.com/rss/0,20514,11661,00.xml";
URL[1] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
for (int f= 0;f < 2;f++)
{
count+=1;
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL[f]); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, 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_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
if (count==2)
{
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) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
}
LogCat:
08-27 09:34:39.786: E/Error:(30651): Expected a quoted string (position:DOCDECL #1:50 in java.io.StringReader#42be4218)
08-27 09:34:39.786: D/AndroidRuntime(30651): Shutting down VM
08-27 09:34:39.786: W/dalvikvm(30651): threadid=1: thread exiting with uncaught exception (group=0x41966da0)
08-27 09:34:39.786: E/AndroidRuntime(30651): FATAL EXCEPTION: main
08-27 09:34:39.786: E/AndroidRuntime(30651): Process: com.androidhive.xmlparsing, PID: 30651
08-27 09:34:39.786: E/AndroidRuntime(30651): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.xmlparsing/com.androidhive.xmlparsing.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.access$900(ActivityThread.java:161)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.os.Handler.dispatchMessage(Handler.java:102)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.os.Looper.loop(Looper.java:157)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.main(ActivityThread.java:5356)
08-27 09:34:39.786: E/AndroidRuntime(30651): at java.lang.reflect.Method.invokeNative(Native Method)
08-27 09:34:39.786: E/AndroidRuntime(30651): at java.lang.reflect.Method.invoke(Method.java:515)
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
08-27 09:34:39.786: E/AndroidRuntime(30651): at dalvik.system.NativeStart.main(Native Method)
08-27 09:34:39.786: E/AndroidRuntime(30651): Caused by: java.lang.NullPointerException
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.androidhive.xmlparsing.AndroidXMLParsingActivity.rssRun(AndroidXMLParsingActivity.java:57)
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.androidhive.xmlparsing.AndroidXMLParsingActivity.onCreate(AndroidXMLParsingActivity.java:38)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.Activity.performCreate(Activity.java:5426)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
I am trying to get data from mysql database and load it into listview ,but not able to do it because the app crashes after the progress dialog appears.The logcat shows error as An error occured while executing doInBackground().Please help me,this is my java file
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class CompScience extends ListActivity{
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://10.0.2.2/books/get_all_books.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "computerscience";
private static final String TAG_PID = "bid";
private static final String TAG_NAME = "title";
private static final String TAG_DESCRIPTION = "author";
// products JSONArray
JSONArray computerscience = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comp_science);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String description = ((TextView) view).getText().toString();
Intent i = new Intent(CompScience.this,List1.class);
// i.putExtra("description", description);
startActivity(i);
}
});
}
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CompScience.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
computerscience = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < computerscience.length(); i++) {
JSONObject c = computerscience.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESCRIPTION, description);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
Log.e(TAG_PRODUCTS, "No products found");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
CompScience.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME,TAG_DESCRIPTION},
new int[] { R.id.bid, R.id.title,R.id.author });
// updating listview
setListAdapter(adapter);
}
});
}
}
This is the logcat
04-08 02:59:40.928: E/AndroidRuntime(2224): FATAL EXCEPTION: AsyncTask #1
04-08 02:59:40.928: E/AndroidRuntime(2224): java.lang.RuntimeException: An error occured while executing doInBackground()
04-08 02:59:40.928: E/AndroidRuntime(2224): at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.lang.Thread.run(Thread.java:841)
04-08 02:59:40.928: E/AndroidRuntime(2224): Caused by: java.lang.NullPointerException
04-08 02:59:40.928: E/AndroidRuntime(2224): at com.example.dashboard.CompScience$LoadAllProducts.doInBackground(CompScience.java:94)
04-08 02:59:40.928: E/AndroidRuntime(2224): at com.example.dashboard.CompScience$LoadAllProducts.doInBackground(CompScience.java:1)
04-08 02:59:40.928: E/AndroidRuntime(2224): at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
04-08 02:59:40.928: E/AndroidRuntime(2224): ... 3 more
Browser response:
{
"computerscience": [
{
"bid": "1",
"title": "Electronic Principles",
"author": "Albert Malvino & David J Bates"
},
{
"bid": "2",
"title": "Electronic Circuits",
"author": "RD Sudhakar"
},
{
"bid": "3",
"title": "Digital Principles & Applications",
"author": "Leach, Malvino, Saha"
}
],
"success": 1
}
Try That:
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
params.add(new BasicNameValuePair(TAG_APPID, appID));
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET",
params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
There pas your required parametrs:
params.add(new BasicNameValuePair(TAG_APPID, appID));
From:
How to connect Android with PHP, MySQL
You have a NullpointerException at line 94:
Log.d("All Products: ", json.toString());
This means that the object json is equal to null (nothing) and trying to call a method from an object that is nothing will throw an error.
Check why jParser.makeHttpRequest(url_all_products, "GET", params); returns null, maybe a parameter is wrong? When it returns a valid result the AsyncTask won't fail again :)
Please look at your doinbackground method, you are writing
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET",params);
Where params are only declared , No params is defined. It all depends on how you are sending params with request in jParser.makeHttpRequest method. I think if this request need params then define some params, or send empty string if no params required.
Thanks
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I am new to android application development. I was doing this tutorial app.
When I run it in the emulator ,it says "Unfortunately AndroidJSONParsingActivity has stopped working.
" There are no errors in the code. The API level is 17 and the emulator is Nexus S.
Please help me out.
I got the tutorial CODE from JSON tutorial
AndroidJsonParsing.java
package com.example.androidjsonparsingactivity;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
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 AndroidJSONParsing extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}
JSONParser.java
package com.example.androidjsonparsingactivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
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.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} 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;
}
}
SingleMenuItemActivity.java
package com.example.androidjsonparsingactivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String cost = in.getStringExtra(TAG_EMAIL);
String description = in.getStringExtra(TAG_PHONE_MOBILE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(description);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidjsonparsingactivity"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.androidjsonparsingactivity.AndroidJSONParsing"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SingleListItem"
android:label="Single Item Selected"></activity>
</application>
</manifest>
Logcat
08-01 07:32:35.531: D/dalvikvm(1121): GC_FOR_ALLOC freed 42K, 7% free 2609K/2792K, paused 37ms, total 41ms
08-01 07:32:35.541: I/dalvikvm-heap(1121): Grow heap (frag case) to 3.288MB for 635812-byte allocation
08-01 07:32:35.591: D/dalvikvm(1121): GC_FOR_ALLOC freed 2K, 6% free 3227K/3416K, paused 47ms, total 47ms
08-01 07:32:35.672: D/dalvikvm(1121): GC_CONCURRENT freed <1K, 6% free 3237K/3416K, paused 9ms+16ms, total 82ms
08-01 07:32:35.740: D/AndroidRuntime(1121): Shutting down VM
08-01 07:32:35.740: W/dalvikvm(1121): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 07:32:35.761: E/AndroidRuntime(1121): FATAL EXCEPTION: main
08-01 07:32:35.761: E/AndroidRuntime(1121): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidjsonparsingactivity/com.example.androidjsonparsingactivity.AndroidJSONParsing}: android.os.NetworkOnMainThreadException
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.Looper.loop(Looper.java:137)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 07:32:35.761: E/AndroidRuntime(1121): at dalvik.system.NativeStart.main(Native Method)
08-01 07:32:35.761: E/AndroidRuntime(1121): Caused by: android.os.NetworkOnMainThreadException
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.example.androidjsonparsingactivity.JSONParser.getJSONFromUrl(JSONParser.java:38)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.example.androidjsonparsingactivity.AndroidJSONParsing.onCreate(AndroidJSONParsing.java:54)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.Activity.performCreate(Activity.java:5104)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-01 07:32:35.761: E/AndroidRuntime(1121): ... 11 more
For Android 4.0 and above you cant do network operations on UI Thread and need to use background threads.
You are calling the following code from the main thread instead of
background thread therefore this exception is thrown .
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
Instead create a async task and perform this in the doInBackground() of the async task
Async task performs the opertaion in background instead of performing it on the main /UI thread
class FetchJsonTask extends AsyncTask<Void, Void, void> {
protected Void doInBackground(Void... params) {
try {
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
} catch (Exception e) {
}
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//code to be executed after background task is finished
}
protected void onPreExecute() {
super.onPreExecute();
//code to be executed before background task is started
}
return null;
}
In onCreate() call the execute the async task in the following way :
new FetchJsonTask().execute();
Related Link:
How to fix android.os.NetworkOnMainThreadException?
you have called the Web from main thread. that's why you have got
Caused by: android.os.NetworkOnMainThreadException
after android 4.0 you cant do network operations on its UIThread. you need to use background threads. i will prefer to use AsyncTask for network call.
Hope it Helps!!
read commented parts and change your code according to that.
class MyAsync extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
// do your JSON parse here
return null;
}
#Override
protected void onPostExecute(Void result) {
// after gettin json data do whatever you want here
super.onPostExecute(result);
}
}
call your async class in your oncreate as:
new MyAsync().execute();
I have the following code but I get an error on this line “userSpinner.setAdapter(adapter);”
private class Task extends AsyncTask<Void, Void, Void>
{
protected void onPreExecute() {
showDialog(DIALOG_TASKING);
}
protected Void doInBackground(Void... JSONArray) {
try
{
HttpGet request = new HttpGet(SERVICE_URI + "/GetBusNames");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject jsonResponse = new JSONObject(new String(buffer));
JSONArray myUsers = jsonResponse.getJSONArray("GetBusNamesResult");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(RealestateActivity.this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Select a Buseness...");
for (int i = 0; i < myUsers.length(); ++i)
{
adapter.add(myUsers.getString(i));
adapter.add(myUsers.getJSONObject(i).getString("BusName"));
}
userSpinner.setAdapter(adapter); // I get an error here if I wrap these two lines in /*...*/ the whole thing loads as expected but the spinner is empty
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
catch (Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_TASKING);
}
}
The following is the Stack Trace produced,
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): FATAL EXCEPTION: AsyncTask #1
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): java.lang.RuntimeException: An error occured while executing doInBackground()
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.os.AsyncTask$3.done(AsyncTask.java:200)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.lang.Thread.run(Thread.java:1096)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.os.Handler.<init>(Handler.java:121)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.widget.Toast.<init>(Toast.java:68)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.widget.Toast.makeText(Toast.java:231)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at com.fnesse.realestate.RealestateActivity.displayExceptionMessage(RealestateActivity.java:271)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at com.fnesse.realestate.RealestateActivity$Task.doInBackground(RealestateActivity.java:131)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at com.fnesse.realestate.RealestateActivity$Task.doInBackground(RealestateActivity.java:1)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at android.os.AsyncTask$2.call(AsyncTask.java:185)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-07 19:54:35.300: ERROR/AndroidRuntime(8741): ... 4 more
11-07 19:56:22.714: ERROR/PowerManagerService(2464): CurLock p:3 mPS:1
11-07 20:06:26.577: ERROR/libnetutils(2464): dhcp start cmd 11 : [dhcpcd:-ABK]
11-07 20:06:27.054: ERROR/HierarchicalStateMachine(2464): TetherMaster - unhandledMessage: msg.what=3
The code works in its own method but not in the AsyncTask.
Any idea’s.
Cheers,
Mike.
You can't perform Display/Update UI inside the doInBackground() method, instead either you can perform by implement runOnUIThread() method or write display/Update statement inside the onPostExecute() method.
In your case, write below statement inside the onPostExecute() and declare JSONArray myUsers at class level:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(RealestateActivity.this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Select a Buseness...");
for (int i = 0; i < myUsers.length(); ++i)
{
adapter.add(myUsers.getString(i));
adapter.add(myUsers.getJSONObject(i).getString("BusName"));
}
userSpinner.setAdapter(adapter); // I get an error here if I wrap these two lines in /*...*/ the whole thing loads as expected but the spinner is empty
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
catch (Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
Final Solution:
private class Task extends AsyncTask<Void, Void, Void>
{
JSONArray myUsers = null;
JSONObject jsonResponse = null; // this is also needed at class level
protected void onPreExecute() {
showDialog(DIALOG_TASKING);
}
protected Void doInBackground(Void... JSONArray) {
try
{
HttpGet request = new HttpGet(SERVICE_URI + "/GetBusNames");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
jsonResponse = new JSONObject(new String(buffer));
}
catch (Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_TASKING);
myUsers = jsonResponse.getJSONArray("GetBusNamesResult");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(RealestateActivity.this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Select a Buseness...");
for (int i = 0; i < myUsers.length(); ++i)
{
adapter.add(myUsers.getString(i));
adapter.add(myUsers.getJSONObject(i).getString("BusName"));
}
userSpinner.setAdapter(adapter); // I get an error here if I wrap these two lines in /*...*/ the whole thing loads as expected but the spinner is empty
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
Use below code inside your onPostExecute method.
userSpinner.setAdapter(adapter);
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
Try this it may help you..
you need to move all the UI manipulation into postExecute method which is executed in the main app thread. Android UI is not thread safe.
Don't do UI related tasks in doInBackground(). Collect your data in doInBackground() and return i from there. Get your data as a parameter to onPostExecute() and issue your userSpinner.* calls there.