I am stuck on this stack trace, I don't know what is reason behind it .
06-27 17:05:14.841: W/SingleClientConnManager(1519): Invalid use of SingleClientConnManager: connection still allocated.
06-27 17:05:14.841: W/SingleClientConnManager(1519): Make sure to release the connection before allocating another one.
06-27 17:05:15.031: E/log_tag(1519): Error in http connection java.net.SocketException: Socket closed
06-27 17:05:15.077: E/log_tag(1519): Error converting result java.lang.NullPointerException
06-27 17:05:15.181: E/log_tag(1519): Error parsing data org.json.JSONException: End of input at character 0 of
06-27 17:05:15.531: W/dalvikvm(1519): threadid=10: thread exiting with uncaught exception (group=0x40014760)
06-27 17:05:15.821: E/AndroidRuntime(1519): FATAL EXCEPTION: AsyncTask #2
06-27 17:05:15.821: E/AndroidRuntime(1519): java.lang.RuntimeException: An error occured while executing doInBackground()
06-27 17:05:15.821: E/AndroidRuntime(1519): at android.os.AsyncTask$3.done(AsyncTask.java:266)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.lang.Thread.run(Thread.java:1020)
06-27 17:05:15.821: E/AndroidRuntime(1519): Caused by: java.lang.NullPointerException
06-27 17:05:15.821: E/AndroidRuntime(1519): at com.si.gtc.Feeds$DownloadJSON.doInBackground(Feeds.java:87)
06-27 17:05:15.821: E/AndroidRuntime(1519): at com.si.gtc.Feeds$DownloadJSON.doInBackground(Feeds.java:1)
06-27 17:05:15.821: E/AndroidRuntime(1519): at android.os.AsyncTask$2.call(AsyncTask.java:252)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-27 17:05:15.821: E/AndroidRuntime(1519): ... 4 more
There are two json responses work at the same time in different activities. If I run single Response above Null pointer error does not affect on my output.
First activity contain tabhost (Tab) . First tab(default tab) has another async task.
This is my first activity wich contain Json call and Tab host.
public class Login_Header extends TabActivity
{
Button Find;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
//To show Custom Title as image
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
//getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.login_header_bar);
super.onCreate(savedInstanceState);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_about_tab);
// Font size has been changed through Styles.xml for tab
TabHost tabHost = getTabHost();
Intent feeds = new Intent(this,Feeds.class);
tabHost.addTab(tabHost.newTabSpec("Tab1")
.setIndicator("Feeds")
.setContent(feeds));
Intent challenges = new Intent(this,Challenges.class);
tabHost.addTab(tabHost.newTabSpec("Tab2")
.setIndicator("Challenges")
.setContent(challenges));
Intent friends = new Intent(this,Friends.class);
tabHost.addTab(tabHost.newTabSpec("Tab3")
.setIndicator("Friends")
.setContent(friends));
Intent group = new Intent(this,Groups.class);
tabHost.addTab(tabHost.newTabSpec("Tab4")
.setIndicator("Groups")
.setContent(group));
Intent details = new Intent(this,Details.class);
tabHost.addTab(tabHost.newTabSpec("Tab5")
.setIndicator("Details")
.setContent(details));
tabHost.setCurrentTab(0);
Find.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent find = new Intent(Login_Header.this,Find.class);
startActivity(find);
}
});
//To call async task
callNotificationCount();
}
private void callNotificationCount()
{
new NotificationCount_Async().execute("");
}
private class NotificationCount_Async extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
try
{
URL url=new URL(getString(R.string.WebServiceURL)+"/notifications/notificationcount");
HttpPost httppost = new HttpPost(url.toString());
HttpResponse responsePOST = LoginPage.httpClient.execute(httppost);
HttpEntity resEntity = responsePOST.getEntity();
InputStream instream = resEntity.getContent();
String result = convertStreamToString(instream);
Log.i("User Feed",result);
return result;
}
catch(Exception ex)
{
Log.e("error", "error", ex);
return null;
}
}
#Override
protected void onPostExecute(String result)
{
try {
JSONObject json = new JSONObject(result);
//Below code is for user count
JSONObject userNotificationjson = json.getJSONObject("user_notification");
if(json.has("user_notification"))
{
String userCount = userNotificationjson.getString("count");
int Count = Integer.parseInt(userCount);
if(Count > 0)
{
LinearLayout llUserCount = (LinearLayout)findViewById(R.id.llUserCount);
TextView userCountTextView =(TextView)findViewById(R.id.txtUserCount);
llUserCount.setVisibility(View.VISIBLE);
userCountTextView.setText(userCount);
}
}
}
private String convertStreamToString(InputStream is)
{
//code
}
Now this is my second activity , Default Tab activity which again have json request.
public class Feeds extends Activity
{
SessionManager session;
String custom_phpsess_id,logged_in_id_User,returnString;
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String FIRST_NAME = "firstname";
static String LAST_NAME = "lastname";
static String ACTION = "action";
// static String ACTIVITY_NAME = "activity_name";
static String IMAGE_URL = "image";
static String USER_ID = "user_id";
static String ACTIVITY_NAME = "activityname";
String strUrl = =new URL(getString(R.string.WebServiceURL)+"/users/userfeeds";
ListView mListView;
String id_User;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get the view from feeds.xml
setContentView(R.layout.feeds);
session = new SessionManager(getApplicationContext());
//To get values from session
HashMap<String, String> User = session.getUserDetails();
logged_in_id_User = User.get(SessionManager.KEY_ID);
custom_phpsess_id = User.get(SessionManager.KEY_USE);
// Creating a new non-ui thread task to download json data
// Execute DownloadJSON AsyncTask
Log.i("On Create", "Main On Create");
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
Log.i("On DownloadJSON", "onPreExecute");
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Feeds.this);
// Set progressdialog title
mProgressDialog.setTitle("");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
Log.i("On doInBackground", "doInBackground");
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrive JSON Objects from the given website URL in JSONfunctions.class
jsonobject = JSONfunctions
.getJSONfromURL(strUrl);
Log.i("On doInBackground-jsonObject", jsonobject.toString());
try
{
// Locate the array name
jsonarray = jsonobject.getJSONArray("userdata");
Log.i("On doInBackground-jsonarray", jsonarray.toString());
for (int i = 0; i < jsonarray.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
if(jsonobject.getString("actions").equals("Completed"))
{
map.put("firstname", jsonobject.getString("first_name"));
map.put("lastname", jsonobject.getString("last_name"));
map.put("action", jsonobject.getString("actions"));
map.put("image", jsonobject.getString("file_name"));
map.put("user_id", jsonobject.getString("id_user"));
map.put("activityname", jsonobject.getString("activity_name"));
Log.i("On doInBackground-Map", map.toString());
// Set the JSON Objects into the array
arraylist.add(map);
}
}
}
catch (JSONException e)
{
Log.i("On doInBackground-JSONException", e.toString());
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args)
{
Log.i("On onPostExecute", "ON post exe");
// Locate the listview in listview_main.xml
listview = (ListView)findViewById(R.id.listview);
Log.i("On onPostExecute-onPostExecute-arraylist", arraylist.toString());
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(Feeds.this, arraylist);
Log.i("On onPostExecute-onPostExecute-Adapter", adapter.toString());
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
and null pointer line is ..
Line no. 97 is = Log.i("On doInBackground-jsonObject", jsonobject.toString());
Related
I am working on a project where data from a mysql database is loaded from my server and displayed in the form of a ListView. However, I am experiencing some hurdles in achieving this where the application ends up force closing whenever I open the ContentActivity. From my logcat, I get two sets of errors:
First I get errors on lines 196 (class LoadAllContent extends AsyncTask<String, String, String> {) and line 221 (Log.d("All Posts: ", json.toString());). The complete error for this segment is:
10-13 13:42:58.978 20090-20315/? W/System.err? at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:221)
10-13 13:42:58.978 20090-20315/? W/System.err? at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:196)
10-13 13:42:58.980 20090-20315/? E/AndroidRuntime? FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.NullPointerException
at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:221)
at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:196)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
10-13 13:42:59.007 553-3073/? W/ActivityManager? Force finishing activity com.app.appname/.ContentActivity
The Second set of errors are at lines 85 (new LoadAllContent().execute();) and line 208 (pDialog.show();)
10-13 13:42:59.856 20090-20090/? E/WindowManager? Activity com.app.appname.ContentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41ec1f80 V.E..... R......D 0,0-480,96} that was originally added here
android.view.WindowLeaked: Activity com.app.appname.ContentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41ec1f80 V.E..... R......D 0,0-480,96} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:424)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.app.appname.ContentActivity$LoadAllContent.onPreExecute(ContentActivity.java:208)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.app.appname.ContentActivity.onCreate(ContentActivity.java:85)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1150)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
What I am not sure of is whether these two errors are related. My ContentActivity.java and index.php files are as below.
ContentActivity.java
public class ContentActivity extends ListActivity implements ISideNavigationCallback {
Utils util;
final Context context = this;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> contentList;
// url to get all content
private static String getContent = "http://192.168.43.87/app/index.php?act=getContent";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_POSTS = "posts";
private static final String TAG_PID = "id";
private static final String TAG_TITLE = "title";
// products JSONArray
JSONArray posts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
util = new Utils(this);
TextView appTit = (TextView) findViewById(R.id.appTitle);
String pageTitle = "MySql Database Content";
appTit.setText((CharSequence)pageTitle);
// Hashmap for ListView
contentList = new ArrayList<HashMap<String, String>>();
new LoadAllContent().execute();
// Get listview
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String postId = ((TextView) view.findViewById(R.id.postId)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), ContentViewActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, postId);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
/**
* Background Async Task to Load all content by making HTTP Request
* */
class LoadAllContent extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ContentActivity.this);
pDialog.setMessage("Loading blog. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All content from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(getContent, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Posts: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
posts = json.getJSONArray(TAG_POSTS);
// looping through All Products
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String title = c.getString(TAG_TITLE);
// 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_TITLE, title);
// adding HashList to ArrayList
contentList.add(map);
}
} else {
// no content found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NoPostActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} 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(
ContentActivity.this, contentList,
R.layout.list_item, new String[] { TAG_PID,
TAG_TITLE},
new int[] { R.id.postId, R.id.title });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
index.php
<?php
$action = $_GET['act'];
if ($action == 'getallposts') {
$posts = get_posts('numberposts=10&order=DESC&orderby=post_desc_gmt');
$numPosts = count($posts);
if ($numPosts > 0) {
$response["posts"] = array();
foreach ($posts as $postr) : setup_postdata( $post );
// temp user array
$post = array();
$post['id'] = $postr->ID;
$post["title"] = $postr->post_title;
$post["desc"] = substr($postr->post_content,0,50).'...';
$post['comments'] = $postr->comment_count;
$post["created"] = $postr->post_date_gmt;
array_push($response["posts"], $post);
endforeach;
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
echo json_encode($response);
}
}
?>
I would really appreciate any pointers to sort out this issue as all the research I have done has not borne any fruit.
Just few comments:
Move Log.d("All Posts: ", json.toString()); to the try .. catch
block and catch for NullPointerException too.
You dont need to use runOnUiThread on the postExecute as
postExecute always runs on the UI thread ( main thread)
Dont start activity from doInBackground ( It might be
possible but dont do it); do this from postExecute rather, like this:
if(success != 1){
Intent i = new
Intent(getApplicationContext(),NoPostActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
I have made an android application where there are a login form, an update details form, etc.
Whenever I enter a wrong detail, the app stops working and a force close dialog box appears.
This is my code:
Login.java
public class AllProductsActivity extends ListActivity
{
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
private static String url_all_products = "http://192.168.1.4/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// 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 Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
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
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// 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);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} 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(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
UpdateDetails.java
public class UpdateDetails extends Activity
{
EditText inputName;
EditText inputAddress;
EditText inputPassword;
EditText confirmPassword;
EditText inputEmailId, inputMobileno;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String resp = "success";
//private static final String Flag = "flag";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.updatedetails);
// Edit Text
inputName = (EditText) findViewById(R.id.editName);
inputAddress = (EditText) findViewById(R.id.editAddress);
inputPassword = (EditText) findViewById(R.id.editPassword);
confirmPassword=(EditText) findViewById(R.id.editConfirmPassword);
inputEmailId=(EditText) findViewById(R.id.editText2_emailid);
inputMobileno=(EditText) findViewById(R.id.editText1_mobile);
// Create button
Button update_details = (Button) findViewById(R.id.buttonUpdate);
// button click event
update_details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (inputPassword == confirmPassword){
// updating user in background thread
new UpdateUserDetails().execute();
}
else {
//Some Sort Of Alert Box
Toast.makeText(getApplicationContext(), "Please Enter Valid Details", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Background Async Task to Create new product
* */
class UpdateUserDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UpdateDetails.this);
pDialog.setMessage("Updating User Details.. Please wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Updating User
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String address = inputAddress.getText().toString();
String password = inputPassword.getText().toString();
String mobileno = inputMobileno.getText().toString();
String emailid = inputEmailId.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("address", address));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("mobile_no", mobileno));
params.add(new BasicNameValuePair("email_id",emailid));
final String url_user = "http://"+ Login.serve +"/catxam/android_update.php";
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_user,"POST", params);
// check log cat from response
Log.d("Update Response", json.toString());
// check for success tag
try {
int success = json.getInt(resp);
if (success == 1) {
// successfully update user
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Can anyone help me in identifying my mistake and help me in rectifying mistakes in my project.
I appreciate your help. Thanks in advance
Here is the logCat window!
02-13 19:32:10.096: E/AndroidRuntime(7328): FATAL EXCEPTION: AsyncTask #2
02-13 19:32:10.096: E/AndroidRuntime(7328): java.lang.RuntimeException: An error occured while executing doInBackground()
02-13 19:32:10.096: E/AndroidRuntime(7328): at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-13 19:32:10.096: E/AndroidRuntime(7328): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.lang.Thread.run(Thread.java:838)
02-13 19:32:10.096: E/AndroidRuntime(7328): Caused by: java.lang.NullPointerException
02-13 19:32:10.096: E/AndroidRuntime(7328): at
com.example.catxam.Login$CreateNewUser.doInBackground(Login.java:146)
02-13 19:32:10.096: E/AndroidRuntime(7328): at com.example.catxam.Login$CreateNewUser.doInBackground(Login.java:1)
02-13 19:32:10.096: E/AndroidRuntime(7328): at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-13 19:32:10.096: E/AndroidRuntime(7328): ... 4 more
Sorry not able to post images :(
Excecute this in postExecute. To display or pass to another activity, Use in postExecute.
Only main operation to be performed in doInBackground.
try {
int success = json.getInt(resp);
if (success == 1) {
// successfully update user
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
As in other answers, your error (althought without logcat....) is that you call:
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
in doInBackground, UI operations are permitted only on UI thread. On the other hand you dont need:
runOnUiThread(new Runnable() {
in onPostExecute because it is already executed on UI thread, so you should use onPostExecute for your toast message.
You cannot make a call to Toast.makeText from the doInBackground method, as it needs to be done on the UI thread.
Do this at the end of doInBackground :
// check for success tag
try {
int success = json.getInt(resp);
String success = success == 1 ? "success" : null;
return success;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
and this in onPostExecute :
protected void onPostExecute(String result) {
if (result!= null) {
// successfully update user
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
}
Additionally, you should not do this in LoadAllProducts:
// updating UI from Background Thread
runOnUiThread(new Runnable()
onPostExecute is designed for you to update the UI at the end of your background task, so you don't need to create an additional Thread to execute that code.
I have this login Activity that contains async task class which perform a parsing method(Post) everything is going right and my data is posted but when the user enters a wrong email and password i just need to Toast him that his email and password are wrong so my code look like this:
public class ActivityLogin extends Activity
{
// Progress Dialog
private ProgressDialog pDialog;
private static String login_tag = "login";
PostParser jsonParser = new PostParser();
// UI references.
private EditText email;
private EditText password;
static String Email="";
static String Password="";
// url to create new product
private static String login_URL = "jhdakjhdakj";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
email=(EditText)findViewById(R.id.email);
password=(EditText)findViewById(R.id.password1);
Button login=(Button)findViewById(R.id.sign_in_button);
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Email=email.getText().toString();
Password=password.getText().toString();
(new LoginInTask()).execute();
}
});
}
class LoginInTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ActivityLogin.this);
pDialog.setMessage("Logging IN..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args)
{
String Email = email.getText().toString();
String Password = password.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Password", Password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(login_URL,"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
int success=0;
try
{
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(int success)
{
if (success==1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), ActivitySignUp.class);
startActivity(i);
// closing this screen
pDialog.dismiss();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
finish();
}
}
}
your help would be appreciated. Thank you
here is my logcat
11-05 16:16:46.536: E/AndroidRuntime(5807): FATAL EXCEPTION: AsyncTask #1
11-05 16:16:46.536: E/AndroidRuntime(5807): java.lang.RuntimeException: An error occured while executing doInBackground()
11-05 16:16:46.536: E/AndroidRuntime(5807): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-05 16:16:46.536: E/AndroidRuntime(5807): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.lang.Thread.run(Thread.java:849)
11-05 16:16:46.536: E/AndroidRuntime(5807): Caused by: java.lang.NullPointerException
11-05 16:16:46.536: E/AndroidRuntime(5807): at com.asap.ActivityLogin$LoginInTask.doInBackground(ActivityLogin.java:108)
11-05 16:16:46.536: E/AndroidRuntime(5807): at com.asap.ActivityLogin$LoginInTask.doInBackground(ActivityLogin.java:1)
11-05 16:16:46.536: E/AndroidRuntime(5807): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-05 16:16:46.536: E/AndroidRuntime(5807): ... 4 more
please change your code with this one I've fixed many things to you taged with <--jack
public class ActivityLogin extends Activity
{
// Progress Dialog
private ProgressDialog pDialog;
private static String login_tag = "login";
PostParser jsonParser;//<-- placed in doinbackground <-- jack
// UI references.
private EditText email;
private EditText password;
static String Email="";
static String Password="";
// url to create new product
private static String login_URL = "jhdakjhdakj";
// JSON Node names
private static final String TAG_SUCCESS = "success";
//Query login <<- jack
LoginInTask query;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
email=(EditText)findViewById(R.id.email);
password=(EditText)findViewById(R.id.password1);
Button login=(Button)findViewById(R.id.sign_in_button);
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Email=email.getText().toString();
Password=password.getText().toString();
//Cancel if already runing or dont excute its up to you <-- jack
if( query != null )
{
query.cancel(true);
}
query = ( LoginInTask ) new LoginInTask().execute();
}
});
}
class LoginInTask extends AsyncTask<String, String, String> {
//Register success here <-- jack
int success=0;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ActivityLogin.this);
pDialog.setMessage("Logging IN..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* if canceled <-- jack
* */
#Override
protected void onCancelled() {
if ( pDialog != null )
{
pDialog.dismiss();
}
}
/**
* Creating product
* */
protected String doInBackground(String... args)
{
String Email = email.getText().toString();
String Password = password.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Password", Password));
//Try from here coz you are working with JSON <<-- jack
try
{
// getting JSON Object
// Note that create product url accepts POST method
//Start new Session <-- jack
jsonParse = new PostParser();
JSONObject json = jsonParser.makeHttpRequest(login_URL,"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e)
{
Log.d("Create Response", "Faild");//<-- tag faild to parse JSON
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(int success)
{
//Check if dialog still runing dismiss <<-- jack
if ( pDialog != null)
{
pDialog.dismiss();
}
if (success==1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), ActivitySignUp.class);
startActivity(i);
}
else
{
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
//finish current activity call it on time only <<-- jack
finish();
}
}
}
I have developed app which connects to server and receive JSON response .Till this it works fine.But then it puts in Hashmap and HashMap in ArrayList to display data.It gives error on while putting Hashmap in ArrayList.My LogCat is
06-03 16:23:10.540: E/AndroidRuntime(15457): FATAL EXCEPTION: AsyncTask #1
06-03 16:23:10.540: E/AndroidRuntime(15457): java.lang.RuntimeException: An error occured while executing doInBackground()
06-03 16:23:10.540: E/AndroidRuntime(15457): at android.os.AsyncTask$3.done(AsyncTask.java:278)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-03 16:23:10.540: E/AndroidRuntime(15457): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.lang.Thread.run(Thread.java:856)
06-03 16:23:10.540: E/AndroidRuntime(15457): Caused by: java.lang.NullPointerException
06-03 16:23:10.540: E/AndroidRuntime(15457): at com.example.project.MainActivity$LoadAllProducts.doInBackground(MainActivity.java:498)
06-03 16:23:10.540: E/AndroidRuntime(15457): at com.example.project.MainActivity$LoadAllProducts.doInBackground(MainActivity.java:1)
06-03 16:23:10.540: E/AndroidRuntime(15457): at android.os.AsyncTask$2.call(AsyncTask.java:264)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-03 16:23:10.540: E/AndroidRuntime(15457): ... 5 more
and my class is
public class asasa extends Activity {
//ListView listView;
Intent intent;
public int currentimageindex=0;
private ProgressDialog pDialog;
Timer timer;
TimerTask task;
ImageView slidingimage;
ProgressDialog progressDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
static final String URL = "http://172.20.55.175/android_connect/get_all_products.php";
private static final String TAG_SUCCESS = "success";
private TextView mStatusView;
private EditText searchEditText;
private static final String TAG_PRODUCTS = "products";
private static final String TAG_NAME = "name";
private static final String TAG_Description = "description";
private static final String TAG_URL = "url";
private static final String TAG_Price = "price";
ListView list;
LazyAdapter adapter;
// flag for Internet connection status
Boolean isInternetPresent = false;
// products JSONArray
JSONArray products = null;
// Connection detector class
ConnectionDetector cd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cd = new ConnectionDetector(getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
LoadAllProducts il = new LoadAllProducts();
il.execute(URL);
}
else
{
// Internet connection is not present
// Ask user to connect to Internet
Toast.makeText(asasa.this, "No Internet Connection You don't have internet connection.", Toast.LENGTH_LONG).show();
}
}
public void longToast(CharSequence message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(asasa.TAG_NAME));
artist.setText(song.get(asasa.TAG_Description));
duration.setText(song.get(asasa.TAG_Price));
imageLoader.DisplayImage(song.get(asasa.TAG_URL), thumb_image);
return vi;
}
}
class LoadAllProducts extends AsyncTask<String, String, String> {
// creating new HashMap
ArrayList<HashMap<String, String>> productsList;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(asasa.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
HashMap<String, String> map = new HashMap<String, String>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(URL, "GET", params);
// Check your log cat for JSON reponse
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length()-1; i++) {
JSONObject c = products.getJSONObject(i);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_Description);
String URl = c.getString(TAG_URL);
String price = c.getString(TAG_Price);
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
map.put(TAG_Description, description);
map.put(TAG_URL, URl);
map.put(TAG_Price, price);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
}
} 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
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(asasa.this, productsList);
list.setAdapter(adapter);
}
}
public void onPause()
{
super.onPause();
if (progressDialog.isShowing()) {
progressDialog.dismiss();
// progressDialog.setCancelable(true);
}
}
}
line 498 is
productsList.add(map);
in protected String doInBackground(String... args)
i cant figure out error...why it is occuring.it is succesfully return json response but can put in hashmap
You haven't initialized your
ArrayList<HashMap<String, String>> productsList;
Initialize it before using.
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> productsList;
This only declares productsList. You never intialized it, so it's null by defaut. You should initialize it:
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String, String>>();
Also usually I recommend using interface in the declaration, so you can later switch interface implementation if needed without much headache. Also specifying minimum visiblity possible is a good OOP practice as it enforces encapsulation.
private List<Map<String, String>> productsList = new ArrayList<HashMap<String, String>>();
Hey i was using the list of friends which gets from the mysql db via php. it sometimes takes a while depends on the connection strenght. so i wanted to use a loader till it gets the data. but im getting errors.
please help me.
thk you,
Code
public class Activity_YourFriendsWith_Class extends Activity {
public String PREFS_NAME = "MyPrefsFile";
public String PREFS_USERID = "prefsUserId";
private static final String TAG_Name = "fname";
private static final String TAG_LName = "lname";
String result = "";
public String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yourfriendswith);
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
userId = pref.getString(PREFS_USERID, "");
Button back = (Button) findViewById(R.id.addback);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(getApplication(), Activity_MyProfile_Class.class);
startActivity(intent);
finish();
}
});
Button addfrnds = (Button) findViewById(R.id.addfrnds);
addfrnds.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inti = new Intent();
inti.setClass(Activity_YourFriendsWith_Class.this,
Activity_AddFreinds_Class.class);
startActivity(inti);
}
});
ProgressTask task = new ProgressTask();
task.execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog pd;
private Activity activity;
#Override
protected Boolean doInBackground(String... arg0) {
// TODO Auto-generated method stub
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("user_id", userId));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://hopscriber.com/friendshopscriber.php");
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 to 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());
}
// parse json data
try {
ArrayList<HashMap<String, String>> placelist = new ArrayList<HashMap<String, String>>();
JSONArray jArray = new JSONArray(result);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Name, json_data.getString("fname"));
map.put(TAG_LName, json_data.getString("lname"));
placelist.add(map);
}
}
ListView list = (ListView) findViewById(R.id.frndslist);
ListAdapter adapter = new SimpleAdapter(activity, placelist,
R.layout.listrow_yourfriendswith, new String[] { TAG_Name,
TAG_LName }, new int[] {
R.id.fname, R.id.lname });
list.setAdapter(adapter);
} catch (JSONException e1) {
ListView list = (ListView) findViewById(R.id.frndslist);
list.setEmptyView(findViewById(R.id.fempty));
}
return null;
}
}
}
Logcat
08-16 18:38:17.910: E/AndroidRuntime(452): FATAL EXCEPTION: AsyncTask #1
08-16 18:38:17.910: E/AndroidRuntime(452): java.lang.RuntimeException: An error occured while executing doInBackground()
08-16 18:38:17.910: E/AndroidRuntime(452): at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.lang.Thread.run(Thread.java:1019)
08-16 18:38:17.910: E/AndroidRuntime(452): Caused by: java.lang.NullPointerException
08-16 18:38:17.910: E/AndroidRuntime(452): at android.widget.SimpleAdapter.<init>(SimpleAdapter.java:85)
08-16 18:38:17.910: E/AndroidRuntime(452): at hopscriber.com.Activity_YourFriendsWith_Class$ProgressTask.doInBackground(Activity_YourFriendsWith_Class.java:142)
08-16 18:38:17.910: E/AndroidRuntime(452): at hopscriber.com.Activity_YourFriendsWith_Class$ProgressTask.doInBackground(Activity_YourFriendsWith_Class.java:1)
08-16 18:38:17.910: E/AndroidRuntime(452): at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-16 18:38:17.910: E/AndroidRuntime(452): ... 4 more
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private Activity activity;
......
ListAdapter adapter = new SimpleAdapter(activity, ......);
}
Variable activity not defined - so you are get NPE
And also you can't manipulate with your ListView inside method doInBackground. You should do this in onPostExecute method
Try to separating your code into different states, do internet connection stuff in doInbackground(), and manipulate your listview in onPostExecute() to make sure the AsyncTask already done its job
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
//load your progressBar here
//for instance
ProgressBar bar = (ProgressBar) findViewById(R.id.yourProgressBar);
bar.setVisibility(View.VISIBLE);
//Load your content here
}
protected void onPostExecute() {
//manipulate your list view here, after fill in some content
//set your loading bar invisible
bar.setVisibility(View.INVISIBLE);
}
}