I'm implementing JSON Parse in Android. The app connect to the url to retrieve JSON and return a String, everything work fine. Now I want to store JSON String to ShareReferences so user still can see the ListView if no internet connection. Here is my code
if (isInternetPresent) { //check internet connection
ServiceHandler sh = new ServiceHandler();
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<TVSchedModel>>();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(URL, ServiceHandler.GET); //connect to url and return a string
Editor editor = sharedpreferences.edit();
editor.putString("JSON", jsonStr);
editor.commit();
} else {
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(),
"Cannot connect to server", Toast.LENGTH_SHORT)
.show();
}
});
jsonStr = sharedpreferences.getString("JSON", "");
Log.i("JSON Shared", jsonStr);
}
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray chan = jsonObj.getJSONArray(TAG_CHANNEL);
for (int i = 0; i < chan.length(); i++) {
listDataHeader.add(chan.getJSONObject(i).getString(
"Channel"));
JSONArray sched = jsonObj.getJSONArray(chan
.getJSONObject(i).getString("Channel"));
List<TVSchedModel> result = new ArrayList<TVSchedModel>();
for (int k = 0; k < sched.length(); k++) {
result.add(convertSchedList(sched.getJSONObject(k)));
}
listDataChild.put(listDataHeader.get(i), result);
}
listAdapter.setHeaderList(listDataHeader);
return listDataChild;
} catch (Throwable t) {
t.printStackTrace();
}
If I have internet connection, the app runs fine. Then I turn off the internet, run the app again and get this error even I got the string back that show at Log.i(...)
04-07 23:59:30.066: W/System.err(22797): java.lang.NullPointerException
04-07 23:59:30.066: W/System.err(22797): at com.pnminh.dfytask.TVSchedFragment$AsyncListViewLoader.doInBackground(TVSchedFragment.java:187)
04-07 23:59:30.066: W/System.err(22797): at com.pnminh.dfytask.TVSchedFragment$AsyncListViewLoader.doInBackground(TVSchedFragment.java:1)
04-07 23:59:30.066: W/System.err(22797): at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-07 23:59:30.066: W/System.err(22797): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
04-07 23:59:30.066: W/System.err(22797): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-07 23:59:30.066: W/System.err(22797): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
04-07 23:59:30.066: W/System.err(22797): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
04-07 23:59:30.066: W/System.err(22797): at java.lang.Thread.run(Thread.java:841)
What did I do wrong here?
Thanks
The error is coming from this line:
listDataHeader.add(chan.getJSONObject(i).getString("Channel"));
My bet is that listDataHeader is null when no connectivity is detected, and this is because you're just initializing this object in this block:
if (isInternetPresent) {
...
}
Simply initialize it outside (above) this block to let it be reachable even when there's no connectivity.
Related
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":"dasdasdasdasd"},{"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();
}
I am trying to build an app with master and detail layout using fragments and data is coming from from parsing JSOnArray by consuming webservice using Asynctask.
No matter what fixes I apply as suggested for similar issues over various forums, I always see this error from logcat:
FATAL EXCEPTION: main
Process: com.example.masterdetail, PID: 26639
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:139)
at com.example.masterdetail.ItemsListFragment.populateResult(ItemsListFragment.java:108) //this is the line where I am building an arraylist in ItemsListFragment.java
at com.example.masterdetail.AsyncRequest.onPostExecute(AsyncRequest.java:147)
at com.example.masterdetail.AsyncRequest.onPostExecute(AsyncRequest.java:23)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
==================
ItemsListFragment.java:
public void populateResult(String response) {
/*TextView resultView = (TextView)getActivity().findViewById(R.id.textUrlContent);
resultView.setText(response);*/
try {
ListView lvItems = (ListView) getActivity().findViewById(R.id.lvItems);
ArrayList<Item> products = new ArrayList<Item>();
JSONObject jsonObject = new JSONObject(response);
JSONObject responseObj = jsonObject.getJSONObject("response");
JSONArray jsonDataProducts = responseObj.getJSONArray("products");
for (int i = 0; i < jsonDataProducts.length(); i++) {
JSONObject oneObject = jsonDataProducts.getJSONObject(i);
Item dataProduct = new Item();
dataProduct.setTitle(oneObject.getString("title"));
dataProduct.setBody(oneObject.getString("id"));
products.add(dataProduct); //***Line: 108 from above error msg ************
}
adapterItems = new ArrayAdapter<Item>(getActivity(),
android.R.layout.simple_list_item_activated_1, products);
lvItems.setAdapter(adapterItems);
lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View item, int position,
long rowId) {
// Retrieve item based on position
Item i = adapterItems.getItem(position);
// Fire selected event for item
listener.onItemSelected(i);
}
});
} catch (Exception e) {
Log.d("ReadRdaJSONFeedTask", e.getLocalizedMessage());
}
}
Log.d("ReadRdaJSONFeedTask", e.getLocalizedMessage());,
The e.getlocalizedMessage() is returning null. Check before calling.
Log.d("ReadRdaJSONFeedTask", e.getLocalizedMessage() == null ? "" : e.getLocalizedMessage());
I am trying to use the Thread to process the data in real time to store 8000 strings in a multi-dimensional array. The logic for storing the array has been tested with a string 8000 numbers, that was successful.
There are two variations for this code the catch (NumberFormatException e) and the catch(NullPointerException e). The logcat for both is listed below. Then it crashes. How do I fix this?
Changing transfer = readMessage; and setting the null to zero did prevent the errors. However, my UI still gets frozen and I get the Force Close or Wait option. Furthermore,
GC_MALLOC and GC_Concurrent are appearing in the error log now.
public double [][]stored = new double[8000][1];
public static HjorthClass finalValue;
public String transfer;
class Task implements Runnable
{
#Override
public void run()
{
try{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
for(int a = 0; a<8000; a++)
{
try
{
double[] convert = new double[1];
for(int z=0; z <1;z++)
{
convert[z]= Double.parseDouble(transfer);
}
for(int j=0; j<1;j++)
{
stored[a][j]= convert[j];
}
}
catch(NumberFormatException e)
{
}
}
finalValue = new HjorthClass(stored);
}}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(final Message msg) {
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf,0,msg.arg1);
String transfer = readMessage;
mConversationArrayAdapter.add("Voltage: "+ transfer);
new Thread(new Task()).start();
break;
logcat with catch(NumberFormatException e)
04-07 06:04:01.712: E/AndroidRuntime(24162): FATAL EXCEPTION: Thread-14
04-07 06:04:01.712: E/AndroidRuntime(24162): java.lang.NullPointerException
04-07 06:04:01.712: E/AndroidRuntime(24162): at org.apache.harmony.luni.util.FloatingPointParser.parseDouble(FloatingPointParser.java:263)
04-07 06:04:01.712: E/AndroidRuntime(24162): at java.lang.Double.parseDouble(Double.java:318)
04-07 06:04:01.712: E/AndroidRuntime(24162): at com.example.android.BluetoothChat.BluetoothChat$Task.run(BluetoothChat.java:248)
04-07 06:04:01.712: E/AndroidRuntime(24162): at java.lang.Thread.run(Thread.java:1019)
logcat with catch(NullPointerException e)
04-07 05:51:55.342: E/AndroidRuntime(23838): FATAL EXCEPTION: Thread-181
04-07 05:51:55.342: E/AndroidRuntime(23838): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-07 05:51:55.342: E/AndroidRuntime(23838): at android.os.Handler.<init>(Handler.java:121)
04-07 05:51:55.342: E/AndroidRuntime(23838): at android.app.Activity.<init>(Activity.java:680)
04-07 05:51:55.342: E/AndroidRuntime(23838): at com.example.android.BluetoothChat.HjorthClass.<init>(HjorthClass.java:18)
04-07 05:51:55.342: E/AndroidRuntime(23838): at com.example.android.BluetoothChat.BluetoothChat$Task.run(BluetoothChat.java:263)
04-07 05:51:55.342: E/AndroidRuntime(23838): at java.lang.Thread.run(Thread.java:1019)
I think the problem is transfer is null,
You can put a condition like this before convert: (the first question which you edit and change your topic)
if(transfer ==null)
transfer="0";
I have a BroadcastReceiver that receives an SMS and then is supposed to immediately send a reply SMS if the text has certain characters. Now it receives and sends the SMSs but it soon forces close giving something like: Unable to start receiver... NullPointerException... ActivityThread.handleReciever (paraphrasing) in the LogCat...what might be the issue? Here's my code, you're looking for the ELSE IF statement(that's the part that I'm currently testing):
public class Service extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction()
.equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String msgFrom;
if (bundle != null) {
try {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
String verificationCode = "717345221";
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
msgFrom = msgs[i].getOriginatingAddress();
String encodeHash = Uri.encode("#");
msgFrom = "0" + msgFrom.substring(4) + encodeHash;
String msgBody = msgs[i].getMessageBody();
if (msgBody.startsWith(verificationCode)) {
this.abortBroadcast();
msgBody = msgBody.substring(verificationCode
.length());
try {
String dial = msgBody + "*" + msgFrom;
Intent call = new Intent(Intent.ACTION_CALL,
Uri.parse("tel:" + dial));
call.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(call);
} catch (Exception e) {
e.toString();
}
} else if (msgBody.contains("TEST123")) {
Toast.makeText(context,
"TEST123 text recieved",
Toast.LENGTH_LONG).show();
String transactionCode = null;
if (msgBody.length() > 9) {
transactionCode = msgBody.substring(0, 9);
}
String attachCode = "776f76wfuh";
String number = msgs[i].getOriginatingAddress();
String message = attachCode + transactionCode;
try {
SmsManager sms = SmsManager.getDefault();
PendingIntent pi = PendingIntent.getBroadcast(
context, 0, new Intent(context,
Service.class), 0);
sms.sendTextMessage(number, null, message, pi,
null);
Toast.makeText(context,
"Text sent with attach code",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO: handle exception
Log.d("Exception caught", e.getMessage());
}
}
}
} catch (Exception e) {
Log.d("Exception caught", e.getMessage());
}
}
}
}
}
Here's the LogCat:
10-31 20:42:05.269: E/AndroidRuntime(15080): FATAL EXCEPTION: main
10-31 20:42:05.269: E/AndroidRuntime(15080): java.lang.RuntimeException: Unable to start receiver com.adbionicpaymentsystem.Service: java.lang.NullPointerException
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1805)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.access$2400(ActivityThread.java:117)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:981)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.os.Handler.dispatchMessage(Handler.java:99)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.os.Looper.loop(Looper.java:130)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-31 20:42:05.269: E/AndroidRuntime(15080): at java.lang.reflect.Method.invokeNative(Native Method)
10-31 20:42:05.269: E/AndroidRuntime(15080): at java.lang.reflect.Method.invoke(Method.java:507)
10-31 20:42:05.269: E/AndroidRuntime(15080): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
10-31 20:42:05.269: E/AndroidRuntime(15080): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
10-31 20:42:05.269: E/AndroidRuntime(15080): at dalvik.system.NativeStart.main(Native Method)
10-31 20:42:05.269: E/AndroidRuntime(15080): Caused by: java.lang.NullPointerException
10-31 20:42:05.269: E/AndroidRuntime(15080): at com.adbionicpaymentsystem.Service.onReceive(Service.java:21)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1794)
10-31 20:42:05.269: E/AndroidRuntime(15080): ... 10 more
be sure to have the permission in your manifest
<uses-permission android:name="android.permission.SEND_SMS"/>
and note that sendTextMessage
This method was deprecated in API level 4.
Use android.telephony.SmsManager.
Problem was I had another service running on the test device that seemingly interferes with this service
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.