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();
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
MainActivity.java
package com.example.yashpachisia.fetchjson;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ActionBarActivity {
String myJSON;
private static final String TAG_RESULTS="result";
private static final String TAG_NAME = "name";
private static final String TAG_AGE = "age";
private static final String TAG_SEX ="sex";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name = c.getString(TAG_NAME);
String age = c.getString(TAG_AGE);
String sex = c.getString(TAG_SEX);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_AGE,age);
persons.put(TAG_SEX,sex);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_AGE,TAG_SEX},
new int[]{R.id.name, R.id.age, R.id.sex}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://localhost/test/form.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/* #Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_user) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yashpachisia.fetchjson">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Logcat window
12-19 17:17:59.353 5132-5132/? D/OpenGLRenderer: Enabling debug mode 0
12-19 17:17:59.353 5132-5132/? D/AndroidRuntime: Shutting down VM
12-19 17:17:59.357 5132-5132/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6299288)
12-19 17:17:59.357 5132-5132/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.example.yashpachisia.fetchjson.MainActivity.showList(MainActivity.java:56)
at com.example.yashpachisia.fetchjson.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:128)
at com.example.yashpachisia.fetchjson.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:89)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
call this method showList() only after checking the result you get in onPostExecute() is not null or empty
if(result != null && result.length >0 ){
myJSON=result;
showList()
}
as your myJson could be empty you are trying to run Json code on it, due to which you are getting NulPointerError
Update
if you are getting the null value it means, that you are not getting the data from the web service or you are calling it wrong.
I saw some mistakes in your code so i wrote you a new one. my code uses commons-io-2.4.jar library but you can always write your own code to see the result
String chartString = "your url which you want to call";
URL chartURL = new URL(chartString);
HttpURLConnection chartHttpURLConnection = (HttpURLConnection) chartURL.openConnection();
chartHttpURLConnection.connect();
String result = IOUtils.toString(chartHttpURLConnection.getInputStream());
System.out.println(""+result);
as you are trying to call the local serve though emulator so the IP address would be 10.0.2.2
so your URL which you would be calling is
URL url = new URL(http://10.0.2.2/test/form.php);
have a look at this IP Address for the Emulator
I am developing an app which includes the upload of all contacts to my server what i am doing is displaying all the contacts and sending them to my server as a string.Here is my code:
package com.example.core.freemusic;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class MainActivity extends Activity {
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (LinearLayout) findViewById(R.id.LinearLayout1);
LoadContactsAyscn lca = new LoadContactsAyscn();
lca.execute();
}
class LoadContactsAyscn extends AsyncTask < Void, Void, String > {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Please Wait","");
}
#Override
protected String doInBackground(Void...params) {
String contacts = "";
Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts += contactName + ":" + phNumber + "\n";
}
c.close();
return contacts;
}
#Override
protected void onPostExecute(String contacts) {
super.onPostExecute(contacts);
pd.cancel();
TextView a = (TextView) findViewById(R.id.textView);
a.setText(contacts);
doInBackground(contacts);
}
protected void doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
try {
httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Actually the code shows no error but on running it in emulator it crashes.
the error on logcat is:
05-24 14:00:57.989 2488-2500/com.example.core.freemusic W/art﹕ Suspending all threads took: 5.841ms
05-24 14:00:57.992 2488-2500/com.example.core.freemusic I/art﹕ Background partial concurrent mark sweep GC freed 1888(115KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 502KB/1014KB, paused 6.923ms total 95.188ms
05-24 14:00:58.073 2488-2488/com.example.core.freemusic I/Choreographer﹕ Skipped 37 frames! The application may be doing too much work on its main thread.
05-24 14:00:58.080 2488-2488/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
05-24 14:00:58.102 2488-2488/com.example.core.freemusic D/AndroidRuntime﹕ Shutting down VM
05-24 14:00:58.103 2488-2488/com.example.core.freemusic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.core.freemusic, PID: 2488
java.lang.IllegalArgumentException: Illegal character in query at index 43: http://192.168.2.30/b.php?username=Sd:(546) 456-4826
Sad:486-44
at java.net.URI.create(URI.java:730)
at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:79)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:64)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:38)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-24 14:01:01.259 2488-2488/com.example.core.freemusic I/Process﹕ Sending signal. PID: 2488 SIG: 9
05-24 15:24:12.790 2685-2685/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
As error code state, you need to encode the query:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
need to changed into:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+java.net.URLEncoder.encode(params[0], "UTF-8"));
I'm doing a small project, and today I had to make a conditional validation in splashscreen. The project was practically finalized when we decided to do this validation in splashscreen.
Modified my class and was working ok, but I had to include the time for the splash disappears (variable SPLASH_TIME_OUT) and started giving an error that I do not understand.
My splashscreen clas (now) is:
package com.clubee.vote;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Splashscreen extends Activity {
// Splash screen timer
private static String url_Pesquisa_voto = "http://dev.clubee.com.br/dbvote/PesquisaVoto.php";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
public String retrieveMacAddress(Context context) {
WifiManager wfman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac address ou wi-fi desabilitado";
}
return macAddress;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new PesquisaVoto().execute();
}
class PesquisaVoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Splashscreen.this);
pDialog.setMessage("Pesquisando Voto..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
int SPLASH_TIME_OUT = 2000;
WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("macAddress", macAddress));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_Pesquisa_voto, "GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(Splashscreen.this, ResultadoFalho.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
} else {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(Splashscreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
The error I am getting is:
03-03 17:38:49.882 10432-10450/com.clubee.vote D/Create Response﹕ {"voto":[{"count":"1"}],"success":1}
03-03 17:38:49.882 10432-10450/com.clubee.vote W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4164dd88)
03-03 17:38:49.892 10432-10450/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.clubee.vote, PID: 10432
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done
Anyone knows what I did wrong? Is it possivel to implement the Runnable inside the IF statement? If I do not put the timeout variable, everything is right.
UPDATE THE LOG WITH ERROR
03-03 22:01:50.016 18731-18746/com.clubee.vote W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4164dd88)
03-03 22:01:50.026 18731-18746/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.clubee.vote, PID: 18731
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.(Handler.java:200)
at android.os.Handler.(Handler.java:114)
at com.clubee.vote.Splashscreen$PesquisaVoto.doInBackground(Splashscreen.java:87)
at com.clubee.vote.Splashscreen$PesquisaVoto.doInBackground(Splashscreen.java:48)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
03-03 22:01:50.697 18731-18731/com.clubee.vote E/WindowManager﹕ android.view.WindowLeaked: Activity com.clubee.vote.Splashscreen has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{44aa2458 V.E..... R......D 0,0-681,345} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:350)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:294)
at com.clubee.vote.Splashscreen$PesquisaVoto.onPreExecute(Splashscreen.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.clubee.vote.Splashscreen.onCreate(Splashscreen.java:44)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
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:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
at dalvik.system.NativeStart.main(Native Method)
03-03 22:01:52.529 18731-18746/com.clubee.vote I/Process﹕ Sending signal. PID: 18731 SIG: 9
Tks in advance for answers and comments. I corrected my code, re-wrote and re-structured it, became easier to see where the mistakes were.
below, I leave the code that is working for future research. thank you very much
package com.clubee.vote;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Splashscreen extends Activity {
// Splash screen timer
private static String url_Pesquisa_voto = "http://dev.clubee.com.br/dbvote/PesquisaVoto.php";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static int SPLASH_TIME_OUT = 2000;
public String retrieveMacAddress(Context context) {
WifiManager wfman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac address ou wi-fi desabilitado";
}
return macAddress;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new PesquisaVoto().execute();
}
}, SPLASH_TIME_OUT);
}
class PesquisaVoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Splashscreen.this);
pDialog.setMessage("Pesquisando Voto..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("macAddress", macAddress));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_Pesquisa_voto, "GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(Splashscreen.this, ResultadoFalho.class);
startActivity(i);
}
else {
Intent i = new Intent(Splashscreen.this, MainActivity.class);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
I cannot clearly see what is wrong based on the Logs you provided but there is something wrong with your structure.
You are starting an Activity within doInBackground Process and then dismissing the Progress Dialog which belongs to the Activity that you just finished.
Try to pass a parameter to the onPostExecute and then finish your Activity there.
And post some more details from your Log to make it clear. There has to be some more logs indicating what went wrong.
I am trying to send a string from a android application to a servlet and then retrieve that string to my android application ,but when i try to invoke the servlet it force close on me
and i dont know why (im very new to android and this is a practice exercise for me)
here is my android simple app:
ANDROID
package com.theopentutorials.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpGetServletActivity extends Activity implements OnClickListener {
Button button;
TextView outputText;
public static String request = "kjo ishte e gjitha";
public static final String URL = ("http://10.0.2.2:8080/HttpGetServlet/HelloWorldServlet?param1=" + request);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}
}
and here is my simple servlet
SERVLET
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String par1 = request.getParameter("param1");
PrintWriter out = response.getWriter();
out.println(par1);
}
}
And the logcat log error says
01-10 13:36:50.014: E/AndroidRuntime(1187): FATAL EXCEPTION: AsyncTask #1
01-10 13:36:50.014: E/AndroidRuntime(1187): java.lang.RuntimeException: An error occured while executing doInBackground()
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.lang.Thread.run(Thread.java:856)
01-10 13:36:50.014: E/AndroidRuntime(1187): Caused by: java.lang.NullPointerException: lock == null
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.Reader.<init>(Reader.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.InputStreamReader.<init>(InputStreamReader.java:122)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.InputStreamReader.<init>(InputStreamReader.java:59)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.getOutputFromUrl(HttpGetServletActivity.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:54)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:1)
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-10 13:36:50.014: E/AndroidRuntime(1187): ... 4 more
doest somebody have any idea ?
Thank you for your help in advance !
Have a nice day!
You need to add the internet access permission
<uses-permission android:name="android.permission.INTERNET"/>
I found that you should use the URLEncoder to encode the url because your url contains spaces. Please check http://developer.android.com/reference/java/net/URLEncoder.html
You have forgot to set param1 from your android app.
connection.setRequestProperty("param1", "Your String Value");
then you will get the value back as response from Servlet.
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.