Check Spinner for Selection before setting Position - java

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.

Related

App has stopped working Android Jsonparser

I am trying to create list view with json .
And this is the Logcat Stacktrace
1215-1239/com.skripsi.mazdamobil E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:186)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:164)
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:841)
Data_Tipsntrick.java:164
private class DownloadList extends AsyncTask<Void,Void,Void> <- line 164
{
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
Data_Tipsntrick.java:186
protected Void doInBackground(Void... unused)
{
String url_param;
url_param="fungsi.php?pl="+filepl+"&kategori="+filekategori;
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
Log.d("log", "url:" + url + url_param);
try
{
JSONArray result = json.getJSONArray("result"); <<-- line 186
for (int i = 0; i < result.length(); i++)
{
JSONObject c = result.getJSONObject(i);
String id = c.getString("id");
String pesan = c.getString("pesan");
String nama_tipsntrick = c.getString("nama");
String kategori_tipsntrick= c.getString("kategori");
HashMap<String,String> map = new HashMap<String,String>();
map.put(in_id,id);
map.put(in_pesan,pesan);
map.put(in_nama,nama_tipsntrick);
map.put(in_kategori,kategori_tipsntrick);
resultList.add(map);
}
Log.d("log", "bla:" + resultList);
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
next
05-05 11:06:11.299 1215-1215/com.skripsi.mazdamobil E/WindowManager﹕ Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
android.view.WindowLeaked: Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.onPreExecute(Data_Tipsntrick.java:173)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.skripsi.mazdamobil.Data_Tipsntrick.onCreate(Data_Tipsntrick.java:66)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Data_Tipsntrick.java:173
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show(); <-- line 173
}
Data_Tipsntrick.java:66
new DownloadList().execute();
What am i doing wrong.Granted i don't know much java.
JSON Response
{"result":[{"id":"7","nama":"sadasdas","kategori":"berkendara","pesan":"dasdasda‌​sdasd"},{"id":"5","nama":"Menggati Ban Bocor","kategori":"berkendara","pesan":"asdsadasdas"}]}
Well you can try this way if you are getting proper JSON response:
...
...
try {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
JSONArray result = json.getJSONArray("result");
if(result!=null) {
for (int i = 0; i < result.length(); i++) {
JSONObject c = (JSONObject) result.get(i);
String id = "", pesan = "", nama_tipsntrick = "", kategori_tipsntrick = "";
if (c.has("id"))
id = c.getString("id");
if (c.has("pesan"))
pesan = c.getString("pesan");
if (c.has("nam"))
nama_tipsntrick = c.getString("nama");
if (c.has("kategori"))
kategori_tipsntrick = c.getString("kategori");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_id, id);
map.put(in_pesan, pesan);
map.put(in_nama, nama_tipsntrick);
map.put(in_kategori, kategori_tipsntrick);
resultList.add(map);
}
}
Log.d("log", "bla:" + resultList);
} catch (JSONException e) {
e.printStackTrace();
}

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

Android ArrayList json connect

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.

FATAL EXCEPTION: AsyncTask, receiving json

Im doing some database work in my app, i want to pull all the locations from my web database and show it in my listview in the app. Ive created the "API" where the respons is Json.
The link where the json is: http://000100023.host56.com/db_all.php
Using this tutorial: http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
The Logcat:
11-14 16:50:21.508: E/AndroidRuntime(22809): FATAL EXCEPTION: AsyncTask #1
11-14 16:50:21.508: E/AndroidRuntime(22809): Process: com.spxc.nightclubratings, PID: 22809
11-14 16:50:21.508: E/AndroidRuntime(22809): java.lang.RuntimeException: An error occured while executing doInBackground()
11-14 16:50:21.508: E/AndroidRuntime(22809): at android.os.AsyncTask$3.done(AsyncTask.java:300)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
11-14 16:50:21.508: E/AndroidRuntime(22809): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.lang.Thread.run(Thread.java:841)
11-14 16:50:21.508: E/AndroidRuntime(22809): Caused by: java.lang.NullPointerException
11-14 16:50:21.508: E/AndroidRuntime(22809): at com.spxc.nightclubratings.SearchLocationActivity$LoadAllProducts.doInBackground(SearchLocationActivity.java:132)
11-14 16:50:21.508: E/AndroidRuntime(22809): at com.spxc.nightclubratings.SearchLocationActivity$LoadAllProducts.doInBackground(SearchLocationActivity.java:1)
11-14 16:50:21.508: E/AndroidRuntime(22809): at android.os.AsyncTask$2.call(AsyncTask.java:288)
11-14 16:50:21.508: E/AndroidRuntime(22809): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
11-14 16:50:21.508: E/AndroidRuntime(22809): ... 4 more
11-14 16:50:22.199: E/WindowManager(22809): android.view.WindowLeaked: Activity com.spxc.nightclubratings.SearchLocationActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42313208 V.E..... R......D 0,0-729,192} that was originally added here
11-14 16:50:22.199: E/WindowManager(22809): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
11-14 16:50:22.199: E/WindowManager(22809): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
11-14 16:50:22.199: E/WindowManager(22809): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.Dialog.show(Dialog.java:286)
11-14 16:50:22.199: E/WindowManager(22809): at com.spxc.nightclubratings.SearchLocationActivity$LoadAllProducts.onPreExecute(SearchLocationActivity.java:119)
11-14 16:50:22.199: E/WindowManager(22809): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
11-14 16:50:22.199: E/WindowManager(22809): at android.os.AsyncTask.execute(AsyncTask.java:535)
11-14 16:50:22.199: E/WindowManager(22809): at com.spxc.nightclubratings.SearchLocationActivity.onCreate(SearchLocationActivity.java:59)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.Activity.performCreate(Activity.java:5243)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread.access$700(ActivityThread.java:135)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
11-14 16:50:22.199: E/WindowManager(22809): at android.os.Handler.dispatchMessage(Handler.java:102)
**11-14 16:50:22.199: E/WindowManager(22809): at android.os.Looper.loop(Looper.java:137)
11-14 16:50:22.199: E/WindowManager(22809): at android.app.ActivityThread.main(ActivityThread.java:4998)
11-14 16:50:22.199: E/WindowManager(22809): at java.lang.reflect.Method.invokeNative(Native Method)
11-14 16:50:22.199: E/WindowManager(22809): at java.lang.reflect.Method.invoke(Method.java:515)
11-14 16:50:22.199: E/WindowManager(22809): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-14 16:50:22.199: E/WindowManager(22809): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
11-14 16:50:22.199: E/WindowManager(22809): at dalvik.system.NativeStart.main(Native Method)
JsonParser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
SearchLocationAcitivity:
public class SearchLocationActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://http://000100023.host56.com/db_all.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "locations";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_location);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
//Intent in = new Intent(getApplicationContext(),
// EditProductActivity.class);
// sending pid to next activity
//in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
//startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchLocationActivity.this);
pDialog.setMessage("Loading locations. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchLocationActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
Any help is much appreciated!
your URL string is wrong, you wrote it like:
Private static String url_all_products = "http://http://000100023.host56.com/db_all.php";
it should be:
Private static String url_all_products = "http://000100023.host56.com/db_all.php";
one http:// is enough ;)
initilize jParser in the onCreate
JSONParser jParser;
in onCreate
jParser = new JSONParser();

Android: Inserting space in an edittext causes a crash

My edit text serves as a search box, and I am getting movies from rotten tomatoes API, using the text inside my edit text, problem is. when a space is inserted the application crashes, I am assuming that I need to convert the spaces into +'s, but I have no clue how where to add this code or how exactly, I hope someone here will be able to help me.
this is my code:
private TextView searchBox;
private Button bGo, bCancelAddFromWeb;
private ListView moviesList;
public final static int ACTIVITY_WEB_ADD = 3;
public List<String> movieTitles;
public List<String> movieSynopsis;
public List<String> movieImgUrl;
private ProgressDialog pDialog;
// the Rotten Tomatoes API key
private static final String API_KEY = "8q6wh77s65a54w433cab9rbsq";
// the number of movies to show
private static final int MOVIE_PAGE_LIMIT = 8;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_add_from_web);
InitializeVariables();
}
/*
* Initializing the variables and creating the bridge between the views from
* the xml file and this class
*/
private void InitializeVariables() {
searchBox = (EditText) findViewById(R.id.etSearchBox);
bGo = (Button) findViewById(R.id.bGo);
bCancelAddFromWeb = (Button) findViewById(R.id.bCancelAddFromWeb);
moviesList = (ListView) findViewById(R.id.list_movies);
bGo.setOnClickListener(this);
bCancelAddFromWeb.setOnClickListener(this);
moviesList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGo:
new RequestTask()
.execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="
+ API_KEY
+ "&q="
+ searchBox.getText()
+ "&page_limit=" + MOVIE_PAGE_LIMIT);
break;
case R.id.bCancelAddFromWeb:
finish();
break;
}
}
private void refreshMoviesList(List<String> movieTitles) {
moviesList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, movieTitles
.toArray(new String[movieTitles.size()])));
}
private class RequestTask extends AsyncTask<String, String, String> {
// make a request to the specified url
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
// make a HTTP request
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
Log.d("Test", "Couldn't make a successful request!");
}
return responseString;
}
// if the request above completed successfully, this method will
// automatically run so you can do something with the response
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MovieAddFromWeb.this);
pDialog.setMessage("Searching...");
pDialog.show();
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
try {
// convert the String response to a JSON object
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray jArray = jsonResponse.getJSONArray("movies");
// add each movie's title to a list
movieTitles = new ArrayList<String>();
// newly added
movieSynopsis = new ArrayList<String>();
movieImgUrl = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject movie = jArray.getJSONObject(i);
movieTitles.add(movie.getString("title"));
movieSynopsis.add(movie.getString("synopsis"));
movieImgUrl.add(movie.getJSONObject("posters").getString(
"profile"));
}
// refresh the ListView
refreshMoviesList(movieTitles);
} catch (JSONException e) {
Log.d("Test", "Couldn't successfully parse the JSON response!");
}
pDialog.dismiss();
}
}
#Override
public void onItemClick(AdapterView<?> av, View view, int position, long id) {
Intent openMovieEditor = new Intent(this, MovieEditor.class);
openMovieEditor.putExtra("movieTitle", movieTitles.get(position));
// newly added
openMovieEditor.putExtra("movieSynopsis", movieSynopsis.get(position));
openMovieEditor.putExtra("movieImgUrl", movieImgUrl.get(position));
openMovieEditor.putExtra("callingActivity", ACTIVITY_WEB_ADD);
startActivityForResult(openMovieEditor, ACTIVITY_WEB_ADD);
}
}
this is the log with the error:
01-14 20:19:19.591: D/Test(907): Couldn't make a successful request!
01-14 20:19:19.690: D/AndroidRuntime(907): Shutting down VM
01-14 20:19:19.700: W/dalvikvm(907): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
01-14 20:19:19.801: E/AndroidRuntime(907): FATAL EXCEPTION: main
01-14 20:19:19.801: E/AndroidRuntime(907): java.lang.NullPointerException
01-14 20:19:19.801: E/AndroidRuntime(907): at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
01-14 20:19:19.801: E/AndroidRuntime(907): at org.json.JSONTokener.nextValue(JSONTokener.java:94)
01-14 20:19:19.801: E/AndroidRuntime(907): at org.json.JSONObject.<init>(JSONObject.java:154)
01-14 20:19:19.801: E/AndroidRuntime(907): at org.json.JSONObject.<init>(JSONObject.java:171)
01-14 20:19:19.801: E/AndroidRuntime(907): at il.jb.projectpart2.MovieAddFromWeb$RequestTask.onPostExecute(MovieAddFromWeb.java:152)
01-14 20:19:19.801: E/AndroidRuntime(907): at il.jb.projectpart2.MovieAddFromWeb$RequestTask.onPostExecute(MovieAddFromWeb.java:1)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.AsyncTask.finish(AsyncTask.java:631)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.Looper.loop(Looper.java:137)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-14 20:19:19.801: E/AndroidRuntime(907): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 20:19:19.801: E/AndroidRuntime(907): at java.lang.reflect.Method.invoke(Method.java:511)
01-14 20:19:19.801: E/AndroidRuntime(907): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-14 20:19:19.801: E/AndroidRuntime(907): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-14 20:19:19.801: E/AndroidRuntime(907): at dalvik.system.NativeStart.main(Native Method)
You should use standard URL encoding as follows:
case R.id.bGo:
new RequestTask()
.execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="
+ API_KEY
+ "&q="
+ URLEncoder.encode(searchBox.getText(), "UTF-8")
+ "&page_limit=" + MOVIE_PAGE_LIMIT);
This will replace spaces and all other non-URL-friendly characters with allowed characters (as defined by RFC 1738 and the HTML spec)
Need to see your logcat to make sure that's the actual problem, but from your code it looks like it is at least one of your issues.
Ideally you'd do something like
String search = searchBox.getText();
search = search.replace(" ", "+");
and then use that variable to send to your RequestTask
Source: Android Developers
Conversely, you may be better off doing a full encoding on the string returned instead of just replacing spaces... as other characters will cause you issues as well (?, &, etc)
EDIT: See EJK's answer for the URLEncoding version.

Categories