Get URL from the database automatically - java

I'm trying to automatically get a URL from my database table online when I click on the button btnDelete. The problem is that it returns the correct values from the database but when try to put it with:
Uri uri = Uri.parse(TAG_url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
It says that "unfortunately, access to database has stopped."
When I make a Log.d() from the TAG_url it returns only "URL" but when I use
txtDesc.setText(product.getString(TAG_url));
it displays correctly the link from the database.
03-14 11:50:18.169: E/Trace(5227): error opening trace file: No such file or directory (2)
03-14 11:50:31.499: E/AndroidRuntime(5227): FATAL EXCEPTION: main
03-14 11:50:31.499: E/AndroidRuntime(5227): java.lang.NullPointerException: uriString
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.net.Uri$StringUri.<init>(Uri.java:464)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.net.Uri$StringUri.<init>(Uri.java:454)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.net.Uri.parse(Uri.java:426)
03-14 11:50:31.499: E/AndroidRuntime(5227): at com.example.androidhive.EditProductActivity1$2.onClick(EditProductActivity1.java:106)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.view.View.performClick(View.java:4084)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.view.View$PerformClick.run(View.java:16966)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.os.Handler.handleCallback(Handler.java:615)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.os.Handler.dispatchMessage(Handler.java:92)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.os.Looper.loop(Looper.java:137)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.app.ActivityThread.main(ActivityThread.java:4745)
03-14 11:50:31.499: E/AndroidRuntime(5227): at java.lang.reflect.Method.invokeNative(Native Method)
03-14 11:50:31.499: E/AndroidRuntime(5227): at java.lang.reflect.Method.invoke(Method.java:511)
03-14 11:50:31.499: E/AndroidRuntime(5227): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-14 11:50:31.499: E/AndroidRuntime(5227): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-14 11:50:31.499: E/AndroidRuntime(5227): at dalvik.system.NativeStart.main(Native Method)
03-14 11:50:44.299: E/Trace(5251): error opening trace file: No such file or directory (2)
Can anybody help me please?
package com.example.androidhive;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EditProductActivity extends Activity {
EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtimg;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;
Button btnvideo;
String pid;
String url;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_product_detials = "http://10.0.2.2/android_connect/get_product_details.php";
// url to update product
private static final String url_update_product = "http://10.0.2.2/android_connect/update_product.php";
// url to delete product
private static final String url_delete_product = "http://10.0.2.2/android_connect/delete_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_img = "img";
private static final String TAG_url = "url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
pid = i.getStringExtra(TAG_PID);
// Getting complete product details in background thread
new GetProductDetails().execute();
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveProductDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// deleting product in background thread
Log.v(TAG_url, "index=");
Uri uri = Uri.parse(TAG_url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Loading movies details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
url = TAG_url;
Log.v(url, "index=");
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// txtimg = (EditText) findViewById(R.id.inputimg);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_url));
txtimg.setText(product.getString(TAG_img));
} else {
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getText(String string) {
// TODO Auto-generated method stub
return null;
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save product Details
* */
class SaveProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Saving product ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String name = txtName.getText().toString();
String price = txtPrice.getText().toString();
String description = txtDesc.getText().toString();
String img = txtimg.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, pid));
params.add(new BasicNameValuePair(TAG_NAME, name));
params.add(new BasicNameValuePair(TAG_PRICE, price));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
params.add(new BasicNameValuePair(TAG_img, img));
params.add(new BasicNameValuePair(TAG_url, url));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_product,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} 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 product uupdated
pDialog.dismiss();
}
}
}

It looks to me that the var TAG_url is intended to be used only as a descriptor, not as a mutable object. First you have: private static final String TAG_url = "url"; defined as a node name. Using that for txtDesc.setText(product.getString(TAG_url)); works because you're retrieving the data associated with the node "url" (which is what TAG_url holds). In that instance, the data is not in the TAG_url var, but uses TAG_url as the key to find the data.
Any log reference to TAG_url will return it's contents: url. By the same token, a parse call using TAG_url will use it's contents as well. Therefore, Uri uri = Uri.parse(TAG_url); is actually calling Uri uri = Uri.parse("url"); - and so the error.
You should replace the TAG_url in the parse call with a var holding the actual url you intend to call. During your database call, you should store that url in a separate var, and parse it instead.
Edit:
Without knowing the structure of your JSON or other data, I can't say for certain. But as example, lets assume that the data returned from the database via the call product.getString(TAG_url) is the data you want sent to the parser. (I'm assuming that since you mentioned the data was correctly set to the TextView txtDesc when called via txtDesc.setText(product.getString(TAG_url));.)
Given that, you could create a field String incomingURL; at the top of the class, and assign the result of the database call like incomingURL = product.getString(TAG_url);. You would then set the TextView with the new field like txtDesc.setText(incomingURL);.
Then, use that variable for your parse: Uri uri = Uri.parse(incomingURL); That would take the data from the database call, and place it in the parser. Just keep in mind that you'll need to check for incomingURL being null if the button is clickable before the database call completes.

Related

Android Listview not working properly?

I've recently been using a tutorial to develop CRUD operations for my android application. The classes contain no errors and the app syncs with my localhost. However, when I want to click a button to view all my user profiles, I get a blank screen but my logCat shows a success message?
Please help!
Class which controls the viewing:
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AllProfile extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> profileList;
// url to get all products list
private static String url_all_profile = "http://MYIPADDRESS:8888/android_connect/get_all_profiles.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERPROFILE = "userprofile";
private static final String TAG_PID = "pid";
private static final String TAG_FIRSTNAME = "firstname";
// products JSONArray
JSONArray userprofile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_profile);
// Hashmap for ListView
profileList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProfile().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(),
EditProfile.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 LoadAllProfile extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProfile.this);
pDialog.setMessage("Loading profiles. 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_profile, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Profiles: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
userprofile = json.getJSONArray(TAG_USERPROFILE);
// looping through All Products
for (int i = 0; i < userprofile.length(); i++) {
JSONObject c = userprofile.getJSONObject(i);
// Storing each json item in variable
String pid = c.getString(TAG_PID);
String firstname = c.getString(TAG_FIRSTNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, pid);
map.put(TAG_FIRSTNAME, firstname);
// adding HashList to ArrayList
profileList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
AddProfile.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(
AllProfile.this, profileList,
R.layout.list_item, new String[] { TAG_PID,
TAG_FIRSTNAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
My php is working as i've debugged it and tested it on HTML and it displays what I want.
logCAT:
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme D/All Profiles:﹕ {"success":1,"UserProfile":[{"updated_at":"0000-00-00 00:00:00","address":"Tottenham Hale","age":"21","created_at":"2015-02-04 21:22:09","gender":"Male","lastname":"Sharma","pid":"4","firstname":"Ankhit","comments":"Help Me"}]}
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ org.json.JSONException: No value for userprofile
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at org.json.JSONObject.getJSONArray(JSONObject.java:544)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at com.example.ankhit.saveme.AllProfile$LoadAllProfile.doInBackground(AllProfile.java:144)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at com.example.ankhit.saveme.AllProfile$LoadAllProfile.doInBackground(AllProfile.java:110)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-04 22:11:59.189 20039-20371/com.example.ankhit.saveme W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
02-04 22:11:59.199 20039-20039/com.example.ankhit.saveme D/AbsListView﹕ unregisterIRListener() is called
02-04 22:11:59.199 20039-20039/com.example.ankhit.saveme D/AbsListView﹕ unregisterIRListener() is called
02-04 22:11:59.209 20039-20039/com.example.ankhit.saveme E/ViewRootImpl﹕ sendUserActionEvent() mView == null
My list view files have no errors. add_profile has a list view with id/list and list_item has two textviews with id/pid and id/name respectively. Any thoughts?
You do not parse the JSON correctly.
"UserProfile" != "userprofile"
To get the values from the JSON, you must use the appropriate keys. Because you use the incorrect keys, org.json.JSONException is thrown, and most of the time, you should take care of thrown exceptions. :)
You need to change this:
private static final String TAG_USERPROFILE = "userprofile";
to
private static final String TAG_USERPROFILE = "UserProfile";

Error parsing dataorg.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

I work in a android app which should show the details of a virtual database(WAMPSERVER i use) and make new documents. When i push the button of show details the app displays the above error.The following is the allproductsactivity.java file.I have see and other similar post but i can't understand and solve my problem. I put x.x.x.x:80 on IP address for security reasons.
AllProductsActivity.java
package com.panos.appphpconnect;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class AllProductsActivity extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://x.x.x.x:80/connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CLASSES = "classes";
private static final String TAG_PID = "_id";
private static final String TAG_NAME = "username";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allproducts);
// 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 _id = ((ListView) view.findViewById(R.id.id)).getAdapter().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, _id);
// 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);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(pDialog!=null && pDialog.isShowing()){
pDialog.cancel();
}
}
/**
* 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 response
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_CLASSES);
// 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.id, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
The code of get_all_products.php is the following
<?php
/*
* Following code will list all the products
*/
// array for json response
$response = array();
// include db connect class
require("db_connect.php");
// connecting to db
$db = new DB_CONNECT();
// get all products from classes table
$result = mysql_query("SELECT *FROM classes") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result)>0) {
// looping through all results
// products node
$response["classes"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$classes = array();
$classes["_id"] = $row["_id"];
$classes["username"] = $row["username"];
$classes["password"] = $row["password"];
// push single product into final response array
array_push($response["classes"], $classes);
}
// success
$response["success"] = 1;
// echoing panos response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No submissions found";
// echo no users json
echo json_encode($response);
}
?>
Also when i run the file get_all_products.php on my browser displays me the error " Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in C:\wamp\www\connect\db_connect.php on line 6" but i don't understand which is line 6 and what is the error.The code of db_connect.php file is the below.
<?php
//A class file to connect to database
class DB_CONNECT{
function_constructor(){
$db = new DB_CONNECT();
//connecting to database
$this->connect();
}
function_destruct(){
//closing db connection
$this->close();
}
//Function to connect with database
function connect(){
//import database connection variables
require_once_DIR_ . '/db_config.php';
//connecting to mysql db
$con=mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD) or die(mysql_error());
//selecting database
$db=mysql_select_db(DB_DATABASE) or die(mysql_error());
//returning connrction cursor
return $con;
}
//function close to db connection
function close(){
//closing db connection
mysql_close();
}
}
?>
That's all errors of logocat
E/JSON Parser(2234): Error parsing dataorg.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
W/dalvikvm(2234): threadid=10: thread exiting with uncaught exception (group=0xb4e1e908)
E/AndroidRuntime(2234): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime(2234): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(2234): at android.os.AsyncTask$3.done(AsyncTask.java:299)
E/AndroidRuntime(2234): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
E/AndroidRuntime(2234): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
E/AndroidRuntime(2234): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
E/AndroidRuntime(2234): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
E/AndroidRuntime(2234): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
E/AndroidRuntime(2234): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
E/AndroidRuntime(2234): at java.lang.Thread.run(Thread.java:856)
E/AndroidRuntime(2234): Caused by: java.lang.NullPointerException
E/AndroidRuntime(2234): at com.panos.appphpconnect.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:141)
E/AndroidRuntime(2234): at com.panos.appphpconnect.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
E/AndroidRuntime(2234): at android.os.AsyncTask$2.call(AsyncTask.java:287)
E/AndroidRuntime(2234): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
E/AndroidRuntime(2234): ... 4 more
SELECT *FROM classes is invalid syntax and when you query you should pass the connection to mysql_query
$result = mysql_query("SELECT * FROM classes", $db) or die(mysql_error());
And forget about android now, get this to work in your browser then you can worry about parsing it in your app.

how do i send parameters using my android app to a remote server using JSON. the code is given below

i am using a reference code for testing ,but when i run the app and click the submit button it shows "Unfortunately your app has Stopped".
Here is my java.class
package com.internship.mtslogin;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class fpasswd extends Activity implements OnClickListener{
private EditText email ;
private Button msubmit;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
private static final String LOGIN_URL ="http://xxx.xxx.x.x:1234/webservice/register.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_passwd);
email = (EditText)findViewById(R.id.email);
msubmit = (Button)findViewById(R.id.submit);
msubmit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(fpasswd.this);
pDialog.setMessage("Please wait, Registering");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String emailid = email.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", emailid));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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 product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(fpasswd.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
But when i run it in a localhost it works fine.
the parameters to be send is only "email".
and url in which i am doing is real server.
i have removed the real url and put a dummy url for string passing.
Can anyone tell me what is going wrong?
here is the logcat details.
FATAL EXCEPTION: AsyncTask #3
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:841)
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
The answer is in the error message. You are missing INTERNET permission. Add to your manifest:
<uses-permission android:name="android.permission.INTERNET"/>
well it looks like you dont have access to the internet.
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
Add this line to the AndroidMainfest.xml to enable the Internet access.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Data not retrieved from previous page, passing from intent

My app requires the data in the page to pass to another page, but apparantly, data are not passed, and I'm unsure of the error. Following is the warning code and error code.
W/System.err(18031): org.json.JSONException: No value for employ
W/System.err(18031): at org.json.JSONObject.get(JSONObject.java:354)
W/System.err(18031): at org.json.JSONObject.getJSONArray(JSONObject.java:548)
W/System.err(18031): at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.doInBackground(EmployeePayslip.java:138)
W/System.err(18031): at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.doInBackground(EmployeePayslip.java:1)
W/System.err(18031): at android.os.AsyncTask$2.call(AsyncTask.java:287)
W/System.err(18031): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
W/System.err(18031): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
W/System.err(18031): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
W/System.err(18031): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
W/System.err(18031): at java.lang.Thread.run(Thread.java:841)
E/ViewRootImpl(18031): sendUserActionEvent() mView == null
This is the code for the java class.
package com.example.splashscreentwo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class EmployeePayslip extends Activity {
private ProgressDialog pDialog;
String pid;
TextView employeeName;
TextView Desc;
TextView txtCreatedAt;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
JSONArray payslip = null;
ArrayList<HashMap<String, String>> payslipList;
// url to get all fulltime employees list
private static String url_payslip = "http://rollit.sg/FYP/ExportPayslip.php";
private static String url_employees = "http://rollit.sg/FYP/Existing_employees_FullTime.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PAYSLIP = "payslip";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PAYSLIPNO = "payslipno";
private static final String TAG_NETSALARY = "netsalary";
private static final String TAG_ISSUEDATE = "issuedate";
private static final String TAG_STARTOFPAYSLIP = "startofpayslip";
private static final String TAG_ENDOFPAYSLIP = "endofpayslip";
private static final String TAG_TYPEOFALLOWANCE = "typeofallowance";
private static final String TAG_ALLOWANCEAMT = "allowanceamt";
private static final String TAG_ALLOWANCEDATE = "allowancedate";
private static final String TAG_AVAILABLEALLOWANCE = "availableallowance";
private static final String TAG_TYPEOFDEDUCTION = "typeofdeduction";
private static final String TAG_DEDUCTIONAMT = "deductionamt";
private static final String TAG_DEDUCTIONDATE = "deductiondate";
private static final String TAG_AGREEDOVERTIMERATE = "agreedovertimerate";
private static final String TAG_OVERTIMERATE = "overtimerate";
private static final String TAG_STARTOFOVERTIMEPERIOD = "startofovertimeperiod";
private static final String TAG_ENDOFOVERTIMEPERIOD = "endofovertimeperiod";
private static final String TAG_BASICSALARY = "basicsalary";
private static final String TAG_EXTRAPAYMENT = "extrapayment";
private static final String TAG_EMPLOYEE = "employ";
private static final String TAG_SALARY = "pay";
private static final String TAG_DESCRIPTION = "description";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.employeepayslip);
payslipList = new ArrayList<HashMap<String, String>>();
// Loading all fulltime employees in Background Thread
// getting employee details from intent
Intent i = getIntent();
// getting employee id (pid) from intent
pid = i.getStringExtra(TAG_PID);
new GetEmployeeDetails().execute();
}
class GetEmployeeDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EmployeePayslip.this);
pDialog.setMessage("Loading employees details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting employee details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("pid", pid));
// getting employee details by making HTTP request
// Note that employee details url will use GET request
JSONObject json = jParser.makeHttpRequest(
url_employees, "GET", params1);
// check your log for json response
Log.d("Employee Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received employee details
JSONArray employeeObj = json
.getJSONArray(TAG_EMPLOYEE); // JSON Array
// get first employee object from JSON Array
JSONObject employee = employeeObj.getJSONObject(0);
// employee with this pid found
// Edit Text
employeeName = (TextView) findViewById(R.id.employeeName);
Desc = (TextView) findViewById(R.id.departmenttext);
// display employee data in EditText
employeeName.setText(employee.getString(TAG_NAME));
Desc.setText(employee.getString(TAG_DESCRIPTION));
}else{
// employee with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
This is the code for the previous page. Data from this page are to pass to the another page above.
package com.example.splashscreentwo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllFTemployeesActivity extends ListActivity
{
LayoutInflater inflater; // Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> employeesList;
// url to get all fulltime employees list
private static String url_employees = "http://rollit.sg/FYP/Existing_employees_FullTime.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_EMPLOYEE = "employee";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
// products JSONArray
JSONArray employee = null; private ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ft_employees);
ImageButton ButtonPT = (ImageButton) findViewById(R.id.btnpt);
ImageButton BtnAddEmployee = (ImageButton) findViewById(R.id.addEmployeeBtn);
BtnAddEmployee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching emplopyee regstration Activity
Intent i = new Intent(getApplicationContext(), RegisterEmployeeActivity.class);
startActivity(i);
finish();
}
});
ButtonPT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching All fulltime employees Activity
Intent i = new Intent(getApplicationContext(), AllPTemployeesActivity.class);
startActivity(i);
finish();
}
});
// Hashmap for ListView
employeesList = new ArrayList<HashMap<String, String>>();
// Loading all fulltime employees in Background Thread
new LoadAllEmployee().execute();
// Get listview
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View header = inflater.inflate(R.layout.planets_heade_view, null);
// lv.addHeaderView(header);
// on seleting single fulltime employee
// launching Edit single fulltime employee 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(),
EmployeePayslip.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 single fulltime employee 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 employee
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all fulltime employees by making HTTP Request
* */
class LoadAllEmployee 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 fulltime employees 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_employees, "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) {
// fulltime employees found
// Getting Array of fulltime employees
employee = json.getJSONArray(TAG_EMPLOYEE);
// looping through All fulltime employees
for (int i = 0; i < employee.length(); i++) {
JSONObject c = employee.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String description= c.getString(TAG_DESCRIPTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESCRIPTION, description);
// adding HashList to ArrayList
employeesList.add(map);
}
} else {
// no fulltime employee found
// Launch Add New employee 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(
AllFTemployeesActivity.this, employeesList,
R.layout.list_item_ft, new String[] { TAG_PID,
TAG_NAME,TAG_DESCRIPTION},
new int[] { R.id.pid, R.id.name, R.id.description});
// updating listview
setListAdapter(adapter);
}
});
}
} }
What is wrong with the codes? Am I missing out something? If so, please guide me along, thanks and i appreciate any help given!
SO there was a spelling error with the string. After correcting the spelling in String, i got this error instead.
E/AndroidRuntime(2421): FATAL EXCEPTION: AsyncTask #4
E/AndroidRuntime(2421): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(2421): at android.os.AsyncTask$3.done(AsyncTask.java:299)
E/AndroidRuntime(2421): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
E/AndroidRuntime(2421): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
E/AndroidRuntime(2421): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
E/AndroidRuntime(2421): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
E/AndroidRuntime(2421): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
E/AndroidRuntime(2421): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
E/AndroidRuntime(2421): at java.lang.Thread.run(Thread.java:841)
E/AndroidRuntime(2421): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
E/AndroidRuntime(2421): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6833)
E/AndroidRuntime(2421): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1082)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.widget.ScrollView.requestLayout(ScrollView.java:2120)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.widget.TableLayout.requestLayout(TableLayout.java:230)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421): at android.widget.TextView.checkForRelayout(TextView.java:7660)
E/AndroidRuntime(2421): at android.widget.TextView.setText(TextView.java:4446)
E/AndroidRuntime(2421): at android.widget.TextView.setText(TextView.java:4283)
E/AndroidRuntime(2421): at android.widget.TextView.setText(TextView.java:4258)
E/AndroidRuntime(2421): at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.doInBackground(EmployeePayslip.java:153)
E/AndroidRuntime(2421): at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.doInBackground(EmployeePayslip.java:1)
E/AndroidRuntime(2421): at android.os.AsyncTask$2.call(AsyncTask.java:287)
E/AndroidRuntime(2421): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
E/AndroidRuntime(2421): ... 4 more
D/AbsListView(2421): onVisibilityChanged() is called, visibility : 0
D/AbsListView(2421): unregisterIRListener() is called
D/AbsListView(2421): unregisterIRListener() is called
E/WindowManager(2421): Activity com.example.splashscreentwo.EmployeePayslip has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42e528b0 V.E..... R.....ID 0,0-640,230} that was originally added here
E/WindowManager(2421): android.view.WindowLeaked: Activity com.example.splashscreentwo.EmployeePayslip has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42e528b0 V.E..... R.....ID 0,0-640,230} that was originally added here
E/WindowManager(2421): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:454)
E/WindowManager(2421): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:258)
E/WindowManager(2421): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
E/WindowManager(2421): at android.app.Dialog.show(Dialog.java:287)
E/WindowManager(2421): at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.onPreExecute(EmployeePayslip.java:111)
E/WindowManager(2421): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
E/WindowManager(2421): at android.os.AsyncTask.execute(AsyncTask.java:534)
E/WindowManager(2421): at com.example.splashscreentwo.EmployeePayslip.onCreate(EmployeePayslip.java:93)
E/WindowManager(2421): at android.app.Activity.performCreate(Activity.java:5372)
E/WindowManager(2421): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
E/WindowManager(2421): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
E/WindowManager(2421): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
E/WindowManager(2421): at android.app.ActivityThread.access$700(ActivityThread.java:168)
E/WindowManager(2421): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
E/WindowManager(2421): at android.os.Handler.dispatchMessage(Handler.java:99)
E/WindowManager(2421): at android.os.Looper.loop(Looper.java:137)
E/WindowManager(2421): at android.app.ActivityThread.main(ActivityThread.java:5493)
E/WindowManager(2421): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(2421): at java.lang.reflect.Method.invoke(Method.java:525)
E/WindowManager(2421): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
E/WindowManager(2421): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
E/WindowManager(2421): at dalvik.system.NativeStart.main(Native Method)
Instead of following in EmployeePayslip
// Loading all fulltime employees in Background Thread
// getting employee details from intent
Intent i = getIntent();
// getting employee id (pid) from intent
pid = i.getStringExtra(TAG_PID);
give a try with following
Bundle extras = getIntent().getExtras();
if (extras != null)
{
pid = extras.getString(TAG_PID);
}
Edited: Seems #user666 is correct. First correct the spelling of TAG_EMPLOYEE in both classes as follow:
private static final String TAG_EMPLOYEE = "employee";

Attempting to follow basic How to connect Android with PHP, MySQL tutorial: application crashes - cannot import android.os.StrictMode

Ok - so I'm using the following tutorial: "How to connect Android with PHP, MySQL"
However almost everyone who attempts the tutorial (judging from the comments) is having force close issues due to the application only being designed to run on API level 8 or earlier.
Several users have developed a fix for this involving adding the following lines of code in EditProductActivity.java file
// this part only to identify where to put the working code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
// NB * insert the line below in import section of EditProductActivity.java
// import android.os.StrictMode;
// Now the code thaat avoid the NetworkOnMainThreadException error
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
However I'm getting messages in my logcat stating StrictMode cannot be resolved and StrictMode cannot be resolved to a type. I've done a bit of research into this and StrictMode is included in API level 8 and above. Taking that into consideration I've raised my API levels in AndroidManifest.xml to:
<uses-sdk android:minSdkVersion="9"
android:targetSdkVersion="9"/>
Then cleaned my project - however I still get StrictMode cannot be resolved to a type errors.
LOGCAT:
03-17 14:06:57.924: D/AndroidRuntime(18472): Shutting down VM
03-17 14:06:57.924: W/dalvikvm(18472): threadid=1: thread exiting with uncaught exception (group=0x41604930)
03-17 14:06:57.924: E/AndroidRuntime(18472): FATAL EXCEPTION: main
03-17 14:06:57.924: E/AndroidRuntime(18472): java.lang.Error: Unresolved compilation problems:
03-17 14:06:57.924: E/AndroidRuntime(18472): The import android.os.StrictMode cannot be resolved
03-17 14:06:57.924: E/AndroidRuntime(18472): StrictMode cannot be resolved to a type
03-17 14:06:57.924: E/AndroidRuntime(18472): StrictMode cannot be resolved to a type
03-17 14:06:57.924: E/AndroidRuntime(18472): StrictMode cannot be resolved
03-17 14:06:57.924: E/AndroidRuntime(18472): at com.example.androidhive.NewProductActivity.<init>(NewProductActivity.java:10)
03-17 14:06:57.924: E/AndroidRuntime(18472): at java.lang.Class.newInstanceImpl(Native Method)
03-17 14:06:57.924: E/AndroidRuntime(18472): at java.lang.Class.newInstance(Class.java:1319)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.os.Handler.dispatchMessage(Handler.java:99)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.os.Looper.loop(Looper.java:137)
03-17 14:06:57.924: E/AndroidRuntime(18472): at android.app.ActivityThread.main(ActivityThread.java:5039)
03-17 14:06:57.924: E/AndroidRuntime(18472): at java.lang.reflect.Method.invokeNative(Native Method)
03-17 14:06:57.924: E/AndroidRuntime(18472): at java.lang.reflect.Method.invoke(Method.java:511)
03-17 14:06:57.924: E/AndroidRuntime(18472): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-17 14:06:57.924: E/AndroidRuntime(18472): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-17 14:06:57.924: E/AndroidRuntime(18472): at dalvik.system.NativeStart.main(Native Method)
JAVA:
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.os.StrictMode;
public class EditProductActivity extends Activity {
EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;
String pid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_product_detials = "http://linkingmanager.zxq.net/get_product_details.php";
// url to update product
private static final String url_update_product = "http://linkingmanager.zxq.net/update_product.php";
// url to delete product
private static final String url_delete_product = "http://linkingmanager.zxq.net/delete_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
pid = i.getStringExtra(TAG_PID);
// Getting complete product details in background thread
new GetProductDetails().execute();
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveProductDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new DeleteProduct().execute();
}
});
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save product Details
* */
class SaveProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Saving product ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String name = txtName.getText().toString();
String price = txtPrice.getText().toString();
String description = txtDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, pid));
params.add(new BasicNameValuePair(TAG_NAME, name));
params.add(new BasicNameValuePair(TAG_PRICE, price));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_product,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} 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 product uupdated
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class DeleteProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Deleting Product...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair> ();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_product, "POST", params);
// check your log for json response
Log.d("Delete Product", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about product deletion
setResult(100, i);
finish();
}
} 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 product deleted
pDialog.dismiss();
}
}
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Since you are using AsyncTask there is no need to setting ThreadPolicy.And don't forget that StrictMode is available starting with 2.3 version.
Update:
Your app is not designated very well. Look at this
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
...
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
...
}
}
Why you're doing that? doInBackground() is directly designed for performing background operations also already runs on background Thread and you shouldn't perform UI update from it. You shouldn't mix it.
If you want to update UI, AsyncTask offers proper methods for achieve it:
onPreExecute()
onProgressUpdate()
onPostExecute()
Hence if you want to update your UI with some information about progress of background task call publishProgress(<data>) method that automatic invokes onProgressUpdate() method and from its update UI.
In your case you are performing initialisation of UI elements in doInBackground() method that you shouldn't.
I suggest you to make this:
Initialise your widgets in onCreate() method.
When you want to update them with data retrieved from
doInBackground() method, call publishProgress() that invoke
onProgressUpdate() method and here perform updating
Here is example:
#Override
protected void onProgressUpdate(String... params) {
txtName.setText(<value>);
...
}
Based on things mentioned above i guess that you need to read AsyncTask tutorial:
So check this
link
Just make sure both your server and the android device is connected to the same wifi connection,make changes in the ip address as your server address for eg: change it to 192.168.1.102(whatever is shown on your server
The code works well and good i have tried it

Categories

Resources