Android ArrayList json connect - java

In my app,I have used ArrayList to display the value.From the ArrayList,values are taken and through JSON results are displayed.But the application is not displaying the value.
I am uploading the code please check and if there any error please help.
actvity
String klno;
TextView tv101;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String url_karmic_lesson = "http://iascpl.com/app/get_karmic_lesson.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_KARMIC = "karmic";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstactivity_xm);
new GetProductDetails().execute();
//tv1.setText("");
//for (int j = 0; j < list.size(); j++){
// tv1.append("KarmicLesson " + list.get(j) + "\n");
//}
TextView tv2 = (TextView) findViewById (R.id.textView2);
tv2.setText(getIntent().getStringExtra("name2"));
}
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FirstActivity.this);
pDialog.setMessage("Loading the result... Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... args)
{
ArrayList<Integer> klno = getIntent().getIntegerArrayListExtra("sum1");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("klno", String.valueOf(klno)));
JSONObject json = jsonParser.makeHttpRequest(
url_karmic_lesson, "GET", params);
Log.d("Single Product Details", json.toString());
try {
int 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
final JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
final TextView tv1 = (TextView) findViewById (R.id.textView1);
final ArrayList<Integer> klno1 = getIntent().getIntegerArrayListExtra("sum1");
runOnUiThread(new Runnable()
{
#Override
public void run()
{
// TODO Auto-generated method stub
try {
//tv1.setText("");
//for (int j = 0; j < list.size(); j++){
// tv1.append("KarmicLesson " + list.get(j) + "\n");
//}
tv1.setText("");
for (int j = 0; j < klno1.size(); j++){
tv1.setText(product.getString(TAG_KARMIC));
}} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}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();
}
}
}
logcat
12-12 12:51:34.797: I/Process(9856): Sending signal. PID: 9856 SIG: 9
12-12 12:59:23.098: D/gralloc_goldfish(10054): Emulator without GPU emulation detected.
12-12 12:59:27.527: D/InputEventConsistencyVerifier(10054): KeyEvent: ACTION_UP but key was not down.
12-12 12:59:27.527: D/InputEventConsistencyVerifier(10054): in android.widget.EditText{40d10060 VFED..CL .F....I. 80,85-400,144 #7f080001 app:id/editText2}
12-12 12:59:27.527: D/InputEventConsistencyVerifier(10054): 0: sent at 27507962000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=27507962, downTime=27507855, deviceId=0, source=0x101 }
12-12 12:59:27.667: D/dalvikvm(10054): GC_CONCURRENT freed 88K, 8% free 2683K/2892K, paused 78ms+12ms, total 225ms
12-12 12:59:37.727: I/Choreographer(10054): Skipped 30 frames! The application may be doing too much work on its main thread.
12-12 12:59:42.397: D/dalvikvm(10054): GC_FOR_ALLOC freed 139K, 9% free 2859K/3120K, paused 558ms, total 599ms
12-12 12:59:42.517: I/dalvikvm-heap(10054): Grow heap (frag case) to 3.513MB for 635812-byte allocation
12-12 12:59:42.867: D/dalvikvm(10054): GC_FOR_ALLOC freed 2K, 8% free 3478K/3744K, paused 348ms, total 348ms
12-12 12:59:43.638: D/dalvikvm(10054): GC_CONCURRENT freed 14K, 8% free 3473K/3744K, paused 18ms+76ms, total 774ms
doing too much work on its main thread.
12-12 13:00:34.857: D/Single Product Details(10054): {"message":"No product found","success":0}
12-12 13:00:38.547: I/Choreographer(10054): Skipped 38 frames! The application may be doing too much work on its main thread.

Related

NullPointer Exception while adding data from android to mysql database [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm getting NullPointerException while adding data from android app to MySQL database, so when I click to create a new product this exception occurs. This is my code to add new product in my database:
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://192.168.56.1/products/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// creating new product in background thread
new CreateNewProduct().execute(name,price,description);
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = args[0],
price = args[1],
description = args[2];
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
**line 102** JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create 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 done
pDialog.dismiss();
}
}
}
I checked out my PHP code and it works fine:
<?php
$con = mysql_connect('localhost', 'root','');
mysql_select_db('database',$con);
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
$sql = "insert into products(name, price, description)
values('$name','$price','$description')";
mysql_query($sql);
?>
Logcat:
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:856)
aused by: java.lang.NullPointerException
at com.example.hanen.test1.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:102)
at com.example.hanen.test1.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:68)
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:856) 
I don't have the answer to your question, because you haven't included line numbers on your listing, and I'm not going to hand-number them. Finding and fixing this type of error, though, is dead simple. Here are the steps:
Turn on line numbers in your IDE
Find the line in your code that corresponds to the topmost line in the stacktrace that refers to a line in your code. In this case that is line 102 in the file NewProductActivity.java
On that line, there will be an expression that looks like variable.something.
When that line is executed variable is null. Find out why.

App Crashes But Method Still Works?

I am trying to delete an item in my listview but keep getting an ArrayOutOfBoundException yet my LOG shows successful deletion from my Localhost and if you open it back it reflects the changes...
Not to sure how to fix the Exception that causes my app to crash? Any Ideas?
Class with Async Tasks:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_locations);
// Hashmap for ListView
profileList = new ArrayList<HashMap<String, String>>();
deleteLocation = (Button) findViewById(R.id.deleteLocation);
locationCount = (TextView) findViewById(R.id.locationCount);
lo = (ListView) findViewById(android.R.id.list);
//setup adapter first //now no items, after getting items (LoadAllLocations) will update it
adapter = new SimpleAdapter(
ViewAllLocations.this, profileList,
R.layout.locationitem, new String[]{TAG_ID,
TAG_LATITUDE, TAG_LONGITUDE},
new int[]{R.id.id, R.id.latitude, R.id.longitude});
// updating listview
setListAdapter(adapter);
// Loading products in Background Thread
new LoadAllLocation().execute();
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
id = i.getStringExtra(TAG_ID);
// Get listview
ListView lo = getListView();
lo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
new DeleteLocation(position).execute();
Map<String, String> item = profileList.get(position);
String selectedItemId = item.get(TAG_ID);
new DeleteLocation(position).execute(selectedItemId);
}
});
}
/**
* **************************************************************
* Background Async Task to Delete Product
*/
class DeleteLocation extends AsyncTask<String, String, Integer> {
int deleteItemPosition;
public DeleteLocation(int position) {
// TODO Auto-generated constructor stub
this.deleteItemPosition = position;
}
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog = new ProgressDialog(ViewAllLocations.this);
//pDialog.setMessage("Deleting Location...");
//pDialog.setIndeterminate(false);
//pDialog.setCancelable(true);
// pDialog.show();
}
/**
* Deleting product
*/
protected Integer doInBackground(String... args) {
String selectedId = args[0];
// Check for success tag
int success = 0; //0=failed 1=success
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", selectedId));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_profile, "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);
//you cant update UI on worker thread, it must be done on UI thread
// Toast.makeText(getApplicationContext(), "Location Deleted",
// Toast.LENGTH_SHORT).show();
//finish();
// }
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(Integer result) {
// dismiss the dialog once product deleted
if (result == 1) {
//success
//delete from list and update listview
profileList.remove(deleteItemPosition);
adapter.notifyDataSetChanged();
//pDialog.dismiss();
} else {
//failed
}
}
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllLocation extends AsyncTask<String, String, Integer> {
int success;
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewAllLocations.this);
pDialog.setMessage("Loading Locations. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected Integer doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_all_profile, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Profiles: ", json.toString());
try {
// Checking for SUCCESS TAG
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
userprofile = json.getJSONArray(TAG_LOCATION);
// looping through All Products
for (int i = 0; i < userprofile.length(); i++) {
JSONObject c = userprofile.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String latitude = c.getString(TAG_LATITUDE);
String longitude = c.getString(TAG_LONGITUDE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LATITUDE, latitude);
map.put(TAG_LONGITUDE, longitude);
// adding HashList to ArrayList
profileList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// UserLocation.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(Integer result) {
// dismiss the dialog after getting all products
pDialog.dismiss();
locationCount.setText("" + profileList.size());
if (result == 1) {
//success
//update adapter items
adapter.notifyDataSetChanged();
} else {
//failed
//launch activity here
}
}
}
LOG: Delete Successful but still an error?
04-25 20:08:32.463 22736-23492/com.example.ankhit.saveme E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
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:856)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.ankhit.saveme.ViewAllLocations$DeleteLocation.doInBackground(ViewAllLocations.java:144)
at com.example.ankhit.saveme.ViewAllLocations$DeleteLocation.doInBackground(ViewAllLocations.java:117)
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:856)
04-25 20:08:32.713 22736-22736/com.example.ankhit.saveme D/AbsListView﹕ unregisterIRListener() is called
04-25 20:08:32.733 22736-23498/com.example.ankhit.saveme D/Delete Product﹕ {"message":"Profile successfully deleted","success":1}
Your problem is originating from here
new DeleteLocation(position).execute();
Map<String, String> item = profileList.get(position);
String selectedItemId = item.get(TAG_ID);
new DeleteLocation(position).execute(selectedItemId);
You are running two separate tasks, but only the second task is given a parameter. Therefore, the first task
new DeleteLocation(position).execute();
throws an exception, here
protected Integer doInBackground(String... args) {
String selectedId = args[0];
...
}
args[0] is out-of-bounds because no args were passed to execute.
The second task is done in a different thread and manages to finish before the exception from the first task is passed back up the call stack, which is why it still "works".

Android.os.NetworkOnMainThreadException Error [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
When i ran my Android Application, I got an android.os.NetworkOnMainThreadException error. I have also added the INTERNET permissions to the manifest file but still it shows this error. Please help advice on what to do. Thanks.
This is my logcat
03-06 11:40:55.721: W/dalvikvm(2142): threadid=1: thread exiting with uncaught exception (group=0x40014760)
03-06 11:40:55.740: E/AndroidRuntime(2142): FATAL EXCEPTION: main
03-06 11:40:55.740: E/AndroidRuntime(2142): android.os.NetworkOnMainThreadException
03-06 11:40:55.740: E/AndroidRuntime(2142): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
03-06 11:40:55.740: E/AndroidRuntime(2142): at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:368)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:208)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:431)
03-06 11:40:55.740: E/AndroidRuntime(2142): at java.net.Socket.connect(Socket.java:901)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-06 11:40:55.740: E/AndroidRuntime(2142): at com.example.testexternaldatabase.JSONParser.makeHttpRequest(JSONParser.java:62)
03-06 11:40:55.740: E/AndroidRuntime(2142): at com.example.testexternaldatabase.EditTicketActivity$GetProductDetails$1.run(EditTicketActivity.java:135)
03-06 11:40:55.740: E/AndroidRuntime(2142): at android.os.Handler.handleCallback(Handler.java:587)
03-06 11:40:55.740: E/AndroidRuntime(2142): at android.os.Handler.dispatchMessage(Handler.java:92)
03-06 11:40:55.740: E/AndroidRuntime(2142): at android.os.Looper.loop(Looper.java:132)
03-06 11:40:55.740: E/AndroidRuntime(2142): at android.app.ActivityThread.main(ActivityThread.java:4025)
03-06 11:40:55.740: E/AndroidRuntime(2142): at java.lang.reflect.Method.invokeNative(Native Method)
03-06 11:40:55.740: E/AndroidRuntime(2142): at java.lang.reflect.Method.invoke(Method.java:491)
03-06 11:40:55.740: E/AndroidRuntime(2142): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
03-06 11:40:55.740: E/AndroidRuntime(2142): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
03-06 11:40:55.740: E/AndroidRuntime(2142): at dalvik.system.NativeStart.main(Native Method)
This is my get_message_details.php file. This file is to accept input as a JSON Array and the messages table will be updated.
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$_GET["pid"] = "1";
// check for post data
if (isset($_GET["pid"])) {
$message_id = $_GET['pid'];
// get a message from messages table
$result = mysql_query("SELECT *FROM messages WHERE message_id = '".$message_id."'");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$message = array();
$message["message_id"] = $result["message_id"];
$message["subject"] = $result["subject"];
$message["type"] = $result["type"];
$message["description"] = $result["description"];
$response["success"] = 1;
// user node
$response["message"] = array();
array_push($response["message"], $message);
// echoing JSON response
echo json_encode($response);
} else {
// no message found
$response["success"] = 0;
$response["message"] = "No message found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no message found
$response["success"] = 0;
$response["message"] = "No message found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
This is my EditTicketActivity.java class.
package com.example.testexternaldatabase;
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.*;
public class EditTicketActivity extends Activity {
EditText txtSubject;
EditText txtType;
EditText txtDesc;
Button btnSave;
Button btnDelete;
String pid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
static GetIPAddress getIPaddress = new GetIPAddress();
// single product url
private static String url_product_details = getIPaddress.getIP()+"get_message_details.php";;
// url to update product
private static String url_update_product = getIPaddress.getIP()+"update_message.php";
// url to delete product
private static String url_delete_product = getIPaddress.getIP()+"delete_message.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "message";
private static final String TAG_PID = "message_id";
private static final String TAG_NAME = "subject";
private static final String TAG_PRICE = "type";
private static final String TAG_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_ticket);
//url_product_details = getIPaddress.getIP()+"get_message_details.php";
//url_update_product = getIPaddress.getIP()+"update_message.php";
//url_delete_product = getIPaddress.getIP()+"delete_message.php";
// save button
btnSave = (Button)findViewById(R.id.editticket_save);
btnDelete = (Button)findViewById(R.id.editticket_delete);
// 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(EditTicketActivity.this);
pDialog.setMessage("Loading Tickets. 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_details, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray messageObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject message = messageObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtSubject = (EditText) findViewById(R.id.editticket_subject);
txtType = (EditText) findViewById(R.id.editticket_type);
txtDesc = (EditText) findViewById(R.id.editticket_description);
// display product data in EditText
txtSubject.setText(message.getString(TAG_NAME));
txtType.setText(message.getString(TAG_PRICE));
txtDesc.setText(message.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(EditTicketActivity.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 subject = txtSubject.getText().toString();
String type = txtType.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, subject));
params.add(new BasicNameValuePair(TAG_PRICE, type));
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(EditTicketActivity.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();
}
}
}
What am I doing wrong here and how could I fix it? :) Thanks!!
You should not use UI element in Asynctask doInBackground() method. Move all UI updation code to onPostExecute() method of the AsyncTask
Example you can refer
AsyncTask Android example

Having log errors while launching activities using intents

I am trying to launch a new activity by passing intents as data
I have posted the log
How to resolve the errors
RatingDescriptionFilterActivity.java
public class RatingDescriptionFilterActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String DISTANCE = "distance";
static String RATING = "rating";
static String FLAG = "flag";
private String url = "----------------- url----------";
String TYPE_FILTER;
String PRICE_FILTER;
String RATE_FILTER;
String DISTANCE_FILTER;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
//Bundle extras = getIntent().getExtras();
TYPE_FILTER = getIntent().getStringExtra("REST1");
PRICE_FILTER = getIntent().getStringExtra("PriceBar");
RATE_FILTER = getIntent().getStringExtra("DistanceBar");
DISTANCE_FILTER = getIntent().getStringExtra("RatingBar");
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(RatingDescriptionFilterActivity.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
String newurl = "?" + "Key=" + DISTANCE_FILTER.trim() + "&Key1=" + RATE_FILTER.trim() + "&Key2=" + PRICE_FILTER.trim() + "&Key3=" + TYPE_FILTER.trim();
Log.i ("newurl", newurl.toString ());
jsonobject = JSONfunctions.getJSONfromURL("------------url-----------"+newurl);
Log.i ("jsonobject", jsonobject.toString ());
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(RatingDescriptionActivity.NAME, jsonobject.getString("restaurantNAME"));
map.put(RatingDescriptionActivity.TYPE, jsonobject.getString("restaurantTYPE"));
map.put(RatingDescriptionActivity.FLAG, "-----url-----"+jsonobject.getString("restaurantIMAGE"));
map.put(RatingDescriptionActivity.DISTANCE, jsonobject.getString("restaurantDISTANCE"));
map.put(RatingDescriptionActivity.RATING, jsonobject.getString("restaurantRATING"));
map.put(RatingDescriptionActivity.PRICE, jsonobject.getString("restaurantPrice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(RatingDescriptionFilterActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Log::
10-21 17:55:46.756: E/AndroidRuntime(1061): FATAL EXCEPTION: AsyncTask #2
10-21 17:55:46.756: E/AndroidRuntime(1061): java.lang.RuntimeException: An error occured while executing doInBackground()
10-21 17:55:46.756: E/AndroidRuntime(1061): at android.os.AsyncTask$3.done(AsyncTask.java:200)
10-21 17:55:46.756: E/AndroidRuntime(1061): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-21 17:55:46.756: E/AndroidRuntime(1061): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-21 17:55:46.756: E/AndroidRuntime(1061): at
line is RatingDescriptionFilterActivity.java:87 is
String newurl = "?" + "Key=" + DISTANCE_FILTER.trim() + "&Key1=" + RATE_FILTER.trim() + "&Key2=" + PRICE_FILTER.trim() + "&Key3=" + TYPE_FILTER.trim();
Problem is arising in getting the value from seek bars in filters.java
How to debug the errors
I hope you are using Eclipse, so you can put breakpoint on this line and debug your application, you can also use expressions view to find out value for each of DISTANCE_FILTER, RATE_FILTER, PRICE_FILTER, TYPE_FILTER
here are steps to debug android application
1) you need to set android:debuggable="true" in your application in the AndroidManifest.xml. if you haven't set that setting, debugging will not be enabled.
2) either start the app by right clicking on the project and select Debug As->Android Application or by running it normally and later in the DDMS perspective select the running app in your devices pane and click on the green bug.
3) once a breakpoint has been hit you can step over (f6) or step into (f5) (check the Run menu for more commands).
Cheers!!!

Check Spinner for Selection before setting Position

I was wondering if it was possible to check that a spinner contains a Value/Selection before setting the position to that value/Selection. What I am doing is that a customer has options for a product EX: RED, YELLOW, GREEN. When they make the selection is it recorded in my DB. When the customer loads that Item to edit I need to set the spinner position to that selection. I can do this with no problems. The problem is that if they log back in and their cart repopulates after a week, an option may no longer be available so I need to make sure that it is still available before the selection. I have tried checking the ArrayList which is what I think I need to do but I am not entirely sure. I did try but it crashes the app. Any Ideas? Thanks in advance. Below is my code.
LOADING THE SELECTED OPTIONS:
ArrayAdapter<String> spinnerOpt1;
ArrayAdapter<String> spinnerOpt2;
ArrayAdapter<String> spinnerOpt3;
class LoadSelectedOptions extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d("CONFIRM SPIN STAT 1::", Integer.toString(SpinStat1));
if(SpinStat1==1){
Log.d("SPINSTAT1", Integer.toString(SpinStat1));
List<NameValuePair> Options = new ArrayList<NameValuePair>();
Options.add(new BasicNameValuePair(DO_FUNCTION, SEL_OPT_FUNCTION1));
Options.add(new BasicNameValuePair(SEL_ITEM_COUNT, theProduct_Number));
JSONObject json = jParser.makeHttpRequest(master_url, "GET", Options);
Log.d("SPINSTAT1", json.toString());
try{
sel_success1 = json.getInt(SEL_SUCCESS1);
JSONArray selected_1 = json.getJSONArray(OPT_CATAGORIES);
if (sel_success1 == 1) {
for (int i = 0; i < selected_1.length(); i++) {
JSONObject c = selected_1.getJSONObject(i);
sel_opt1 = c.getString(SEL_OPT1);
}
}else {
}
}catch (JSONException e) {
e.printStackTrace();
}
}
if(SpinStat2==1){
List<NameValuePair> Options2 = new ArrayList<NameValuePair>();
Options2.add(new BasicNameValuePair(DO_FUNCTION, SEL_OPT_FUNCTION2));
Options2.add(new BasicNameValuePair(SEL_ITEM_COUNT, theProduct_Number));
JSONObject json2 = jParser.makeHttpRequest(master_url, "GET", Options2);
try{
sel_success2 = json2.getInt(SEL_SUCCESS2);
JSONArray selected_2 = json2.getJSONArray(OPT_CATAGORIES);
if (sel_success2 == 1) {
for (int i = 0; i < selected_2.length(); i++) {
JSONObject c = selected_2.getJSONObject(i);
sel_opt2 = c.getString(SEL_OPT2);
}
}else {
}
}catch (JSONException e) {
e.printStackTrace();
}
}
if(SpinStat3==1){
List<NameValuePair> Options3 = new ArrayList<NameValuePair>();
Options3.add(new BasicNameValuePair(DO_FUNCTION, SEL_OPT_FUNCTION3));
Options3.add(new BasicNameValuePair(SEL_ITEM_COUNT, theProduct_Number));
JSONObject json3 = jParser.makeHttpRequest(master_url, "GET", Options3);
try{
sel_success3 = json3.getInt(SEL_SUCCESS3);
JSONArray selected_3 = json3.getJSONArray(OPT_CATAGORIES);
if (sel_success3 == 1) {
for (int i = 0; i < selected_3.length(); i++) {
JSONObject c = selected_3.getJSONObject(i);
sel_opt3 = c.getString(SEL_OPT3);
}
}else {
}
}catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
//SpinStat is a value determining if there are options. 0==No Options 1==Options Are Available
if(SpinStat1==1){
//spinnerOpt1 is the ArrayAdapter for that specific spinner. It is loaded from a List/ArrayList "options1"
}else if(spinnerOpt1.equals(sel_opt1)){
Spinner1.setSelection(spinnerOpt1.getPosition(sel_opt1));
}
if(SpinStat2==1){
}else if(spinnerOpt2.equals(sel_opt2)){
Spinner2.setSelection(spinnerOpt2.getPosition(sel_opt2));
}
if(SpinStat3==1){
}else if(spinnerOpt3.equals(sel_opt3)){
Spinner3.setSelection(spinnerOpt3.getPosition(sel_opt3));
}
}
});
}
}
LOGCAT::
07-16 13:41:49.875: E/AndroidRuntime(20378): FATAL EXCEPTION: main
07-16 13:41:49.875: E/AndroidRuntime(20378): java.lang.NullPointerException
07-16 13:41:49.875: E/AndroidRuntime(20378): at com.example.shopper.EditCart$LoadSelectedOptions$1.run(EditCart.java:689)
07-16 13:41:49.875: E/AndroidRuntime(20378): at android.app.Activity.runOnUiThread(Activity.java:4784)
07-16 13:41:49.875: E/AndroidRuntime(20378): at com.example.shopper.EditCart$LoadSelectedOptions.onPostExecute(EditCart.java:675)
07-16 13:41:49.875: E/AndroidRuntime(20378): at com.example.shopper.EditCart$LoadSelectedOptions.onPostExecute(EditCart.java:1)
07-16 13:41:49.875: E/AndroidRuntime(20378): at android.os.AsyncTask.finish(AsyncTask.java:631)
07-16 13:41:49.875: E/AndroidRuntime(20378): at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-16 13:41:49.875: E/AndroidRuntime(20378): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
07-16 13:41:49.875: E/AndroidRuntime(20378): at android.os.Handler.dispatchMessage(Handler.java:99)
07-16 13:41:49.875: E/AndroidRuntime(20378): at android.os.Looper.loop(Looper.java:137)
07-16 13:41:49.875: E/AndroidRuntime(20378): at android.app.ActivityThread.main(ActivityThread.java:4898)
07-16 13:41:49.875: E/AndroidRuntime(20378): at java.lang.reflect.Method.invokeNative(Native Method)
07-16 13:41:49.875: E/AndroidRuntime(20378): at java.lang.reflect.Method.invoke(Method.java:511)
07-16 13:41:49.875: E/AndroidRuntime(20378): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
07-16 13:41:49.875: E/AndroidRuntime(20378): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
07-16 13:41:49.875: E/AndroidRuntime(20378): at dalvik.system.NativeStart.main(Native Method)
LOADING OPTIONS TO SPINNER::
class LoadOptions1 extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(DO_FUNCTION, OPT_FUNCTION));
params.add(new BasicNameValuePair("PROD_ID", GET_PID));
// getting JSON string from URL
Log.d("PROD_ID", GET_PID);
Log.d("DO_FUNCTION", OPT_FUNCTION);
Log.d("master_url", master_url);
JSONObject json = jParser.makeHttpRequest(master_url, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Options: ", json.toString());
// Checking for SUCCESS TAG
success2 = json.getInt(OPT_SUCCESS);
Log.d("success2", Integer.toString(success2));
if (success2 == 1) {
// products found
// Getting Array of Products
JSONArray catagories = json.getJSONArray(OPT_CATAGORIES);
// looping through All Products
for (int i = 0; i < catagories.length(); i++) {
JSONObject c = catagories.getJSONObject(i);
// Storing each json item in variable
String category = c.getString(OPT_CATAGORY);
options1.add(category);
}
} 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
if (!(success2 == 0)) {
SpinStat1 = 1;
Log.d("SET SPIN STAT 1::", Integer.toString(SpinStat1));
spinnerOpt1 = new ArrayAdapter<String>(EditCart.this, android.R.layout.simple_list_item_1, options1);
Spinner1.setAdapter(spinnerOpt1);
// MySpinner.setSelection(spinnerMenu.getPosition("Select A Catagory"));
}else{
textView8.setVisibility(View.GONE);
Spinner1.setVisibility(View.GONE);
SpinStat1 = 0;
}
}
}
THE ANSWER:: Check the value against the list.
if(SpinStat1==1){
}else if(options1.contains(sel_opt1)){
Spinner1.setSelection(spinnerOpt1.getPosition(sel_opt1));
}
Oh, I see the problem. Your ArrayAdapters are null. You never initialize them
ArrayAdapter<String> spinnerOpt1;
ArrayAdapter<String> spinnerOpt2;
ArrayAdapter<String> spinnerOpt3;
you need to initialize these somewhere beore using them in onPostExecute()
This is assuming line 689 is else if(spinnerOpt1.equals(sel_opt1)), from what I see. If not then you may have other problems, also, but those need to be initialized
Check the Value "RED" against the List that populates the Adapter. Code is posted above.

Categories