Handler{40664220} sending message to a Handler on a dead thread - java

I am getting this error my code is, can anyone help please
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new FetchAddressTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Constants.USER_CURRENT_LOCATION);
else
new FetchAddressTask().execute(Constants.USER_CURRENT_LOCATION);
class FetchAddressTask extends AsyncTask<LatLng, String, String> {
#Override
protected void onPreExecute() {
// showDialog();
// showMyDialog();
DialogHelper.showTrasparentDialog(EnterBikeInfoActivity.this);
super.onPreExecute();
}
#Override
protected String doInBackground(LatLng... latLngs) {
String result = getCurrentLocationViaJSON(latLngs[0].latitude, latLngs[0].longitude);
if (result == null)
result = "";
return result;
}
#Override
protected void onPostExecute(String result) {
if (result == null || result.length() == 0) {
DialogHelper.showDialogMessage(BikeApp.getInstance(), "Unable to retrieve the address.");
} else {
addressEditText.setText(result);
}
DialogHelper.dismissTransparentDialog();
super.onPostExecute(result);
}
}
public String getCurrentLocationViaJSON(double lat, double lng) {
JSONObject jsonObj = getLocationInfo(lat, lng);
Log.i("JSON string =>", jsonObj.toString());
String currentLocation = "testing";
// String street_address = null;
// String postal_code = null;
try {
String status = jsonObj.getString("status").toString();
Log.i("status", status);
if (status.equalsIgnoreCase("OK")) {
JSONArray results = jsonObj.getJSONArray("results");
int i = 0;
Log.i("i", i + "," + results.length()); // TODO delete this
JSONObject r0 = results.getJSONObject(i);
String v = r0.getString("formatted_address");
currentLocation = v;
Log.i("JSON Geo Locatoin =>", currentLocation);
return currentLocation;
}
} catch (JSONException e) {
Log.e("testing", "Failed to load JSON");
e.printStackTrace();
}
return "";
}
getLocationInfo(lat, lng); funtion fetches address info from an http request, my flow is coming into FetchAddressTask doInBackground with correct address but when it return the address it give me this error message.
11-25 11:20:01.746: W/MessageQueue(2593): Handler{40664220} sending message to a Handler on a dead thread
11-25 11:20:01.746: W/MessageQueue(2593): java.lang.RuntimeException: Handler{40664220} sending message to a Handler on a dead thread
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.MessageQueue.enqueueMessage(MessageQueue.java:196)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.Handler.sendMessageAtTime(Handler.java:457)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.Handler.sendMessageDelayed(Handler.java:430)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.Handler.sendMessage(Handler.java:367)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.Message.sendToTarget(Message.java:349)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.AsyncTask$3.done(AsyncTask.java:214)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.FutureTask$Sync.innerSet(FutureTask.java:253)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.FutureTask.set(FutureTask.java:113)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:311)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
11-25 11:20:01.746: W/MessageQueue(2593): at java.lang.Thread.run(Thread.java:1019)

Related

Android volley weird error

I'm developing an android aplication using a webservice in php.
Everything was working until now.
To comunicate android and php I'm using the volley library, and everything is working but this.
I don't know if it is something such a maximum number of parameters or what.
Anything is truly null,
I've test something, when I send half the parameters it "works", it returns me error 500, but at least it sends something.
When I try to send all the parameters, this weird error shows up.
here is my code, and the error:
public void inserePagamento(final Context ctx, DocTed docTed,
final ProgressDialog ringProgressDialog) {
String url = "http://192.168.1.168/declabank/ws/public/transacaoDocTed";
Encriptador cesar = Encriptador.getInstance();
HashMap<String, String> params = new HashMap<String, String>();
params.put("agencia", usuario.getAgencia());
params.put("conta", usuario.getConta());
params.put("cripto",cesar.encriptar(cesar.getChave(), usuario.getNome()));
params.put("docFavorecidoNome", docTed.getNomeFav());
params.put("docFavorecidoCompensacao", docTed.getCodComp());
params.put("docFavorecidoBanco", docTed.getCodBanco());
params.put("docFavorecidoAgencia", docTed.getnAgencia());
params.put("docFavorecidoConta", docTed.getnConta());
params.put("docFavorecidoCPFCNPJ", docTed.getCpfCnpj());
params.put("docFavorecidoTipo", docTed.getDocFTipo());
params.put("docTed", "" + docTed.getDocTed());
params.put("docFinalidadeTransacao", docTed.getFinalidadeCod());
params.put("docTitularidade", docTed.getTipoDoc());
params.put("docValor", docTed.getValor());
params.put("docData", docTed.getData());
params.put("docRemetenteNome", docTed.getNomeRemetente());
params.put("docRemetenteCPFCNPJ", docTed.getCpfCnpjRemetente());
params.put("docRemetenteConta", docTed.getContaRemetente());
params.put("CXC_COD_CX", docTed.getCodCx());
params.put("docOrigem", docTed.getOrigem());
params.put("docStatus", "" + docTed.getStatus());
params.put("docComprovante", docTed.getComprovante());
params.put("docTransferirEm", docTed.getTransferirEm());
params.put("docAgendado", "" + docTed.getAgendado());
RequestQueue rq = Volley.newRequestQueue(ctx);
DeclaJSONArrayRequest djson = new DeclaJSONArrayRequest(Method.POST,
url, params, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray responseArray) {
try {
JSONObject response = responseArray
.getJSONObject(0);
try {
Log.e("DocTed", "DocTed gravado");
Log.e("DocTed", "DocTed gravado");
Log.e("DocTed", "DocTed gravado");
Log.e("DocTed", "DocTed gravado");
Log.e("DocTed", "DocTed gravado");
String erro = response.getString("erro");
ringProgressDialog.dismiss();
Toast.makeText(ctx, erro, Toast.LENGTH_LONG)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error != null) {
Toast.makeText(ctx, "Erro: ", Toast.LENGTH_LONG)
.show();
Log.e("Erro", "" + error.getMessage());
} else {
Toast.makeText(ctx, "Erro: " + error.getMessage(),
Toast.LENGTH_LONG).show();
Log.e("Erro", "Treta da Grossa");
}
}
});
djson.setTag("TagPagamento");
djson.setRetryPolicy((RetryPolicy) new DefaultRetryPolicy(15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(djson);
}
error:
11-25 11:46:17.556: E/Volley(4874): [404] NetworkDispatcher.run: Unhandled exception java.lang.NullPointerException
11-25 11:46:17.556: E/Volley(4874): java.lang.NullPointerException
11-25 11:46:17.556: E/Volley(4874): at libcore.net.UriCodec.encode(UriCodec.java:132)
11-25 11:46:17.556: E/Volley(4874): at java.net.URLEncoder.encode(URLEncoder.java:57)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.Request.encodeParameters(Request.java:463)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.Request.getBody(Request.java:449)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:236)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:210)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:106)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:110)
11-25 11:46:21.496: E/Erro(4874): java.lang.NullPointerException
you will get this exception, when the any of the params value is null.
Check your value parameters in params.

Android: Unable to find resource ID Exception

In my Android application i am creating a pie chart using achartengine library. When click a button it takes data from sqlite database and draw a pie chart. This is my code segment.
btnpieChart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SelectDBAdapter selectDBAdapter = SelectDBAdapter
.getDBAdapterInstance(getActivity());
try {
selectDBAdapter.openDataBase();
chartDataMap = selectDBAdapter
.getPieChartData(strBusinessUnit,
currentPeriod, currentYear);
} catch (Exception e) {
selectDBAdapter.close();
e.printStackTrace();
} finally {
selectDBAdapter.close();
}
System.out.println("chartDataMap === "+ chartDataMap);
if (chartDataMap.size() > 0) {
for (Map.Entry<String, Double> entry : chartDataMap.entrySet()) {
lstBrandNames.add(entry.getKey());
lstAchievedVals.add(entry.getValue());
}
ArrayList<Double> distribution = calc_Percentage(lstAchievedVals);
System.out.println("distribution === " + distribution);
lstBrandNames = set_lables(lstBrandNames, distribution);
CategorySeries distributionSeries = new CategorySeries(
"Brands - Achievement Progress");
for (int i = 0; i < distribution.size(); i++) {
distributionSeries.add(lstBrandNames.get(i), distribution.get(i));
}
DefaultRenderer defaultRenderer = new DefaultRenderer();
defaultRenderer.setApplyBackgroundColor(true);
defaultRenderer.setBackgroundColor(Color.WHITE);
for (int i = 0; i < distribution.size(); i++) {
SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
seriesRenderer.setColor(color);
seriesRenderer.setGradientEnabled(false);
seriesRenderer.setDisplayChartValues(true);
seriesRenderer.setShowLegendItem(false);
defaultRenderer.setLabelsTextSize(25);
defaultRenderer.addSeriesRenderer(seriesRenderer);
}
defaultRenderer.setLabelsColor(Color.BLACK);
defaultRenderer.setChartTitle("Brands - Achievement Progress");
defaultRenderer.setChartTitleTextSize(30);
defaultRenderer.setZoomButtonsVisible(true);
defaultRenderer.setShowLabels(true);
FragmentTransaction ft = getFragmentManager().beginTransaction();
mChartView = ChartFactory.getPieChartView(getActivity(), distributionSeries, defaultRenderer);
ft.replace(mChartView.getId(), new DummySectionFragment(), "NewFragmentTag");
ft.addToBackStack(null);
ft.commit();
}
}
});
My mChartView is,
private GraphicalView mChartView = null;
Log cat says:
11-25 07:03:58.311: E/AndroidRuntime(2706): FATAL EXCEPTION: main
11-25 07:03:58.311: E/AndroidRuntime(2706): android.content.res.Resources$NotFoundException: Unable to find resource ID #0xffffffff
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.content.res.Resources.getResourceName(Resources.java:1659)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Handler.handleCallback(Handler.java:725)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Handler.dispatchMessage(Handler.java:92)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Looper.loop(Looper.java:137)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.app.ActivityThread.main(ActivityThread.java:5039)
11-25 07:03:58.311: E/AndroidRuntime(2706): at java.lang.reflect.Method.invokeNative(Native Method)
11-25 07:03:58.311: E/AndroidRuntime(2706): at java.lang.reflect.Method.invoke(Method.java:511)
11-25 07:03:58.311: E/AndroidRuntime(2706): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-25 07:03:58.311: E/AndroidRuntime(2706): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-25 07:03:58.311: E/AndroidRuntime(2706): at dalvik.system.NativeStart.main(Native Method)
I would be much obliged if anyone could explain what's going on here and how can I solve this issue.
Thanks
Check these lines
mChartView = ChartFactory.getPieChartView(getActivity(), distributionSeries, defaultRenderer);
ft.replace(mChartView.getId(), new DummySectionFragment(), "NewFragmentTag");
especially mChartView.getId() log this value and check it with what you expected

Unable to start receiver NullPointerException

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

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.

SQLite crashes when trying to enter a String with a space

I am creating an application that has a default table that stores what the other tables are so that when your trying to put your own input into the app it will store the tables but when you try to add a table to the default table it works perfectly unless there is a space "test" would work perfect "test 1" would crash the app. This is my code retrieving the String that is inputed by the user:
t = new Table(this);
t.open();
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
rListName = input.getText().toString();
t.createNew(rListName + "DB");
t.createList(rListName, rListName + "DB");
t.close();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
This is my createNew and createList:
public void createNew(String TABLE_NAME){
if(DATABASE_STATUS == "new"){
ourHelper.createNew(ourDatabase, TABLE_NAME);
System.out.println("Creating " + TABLE_NAME);
}else{
System.out.print("Already Created");
}
}
public long createList(String listName, String listDB){
ContentValues cv = new ContentValues();
cv.put(KEY_LISTNAME, listName);
cv.put(KEY_LISTDB, listDB);
return ourDatabase.insert(DEFAULT_TABLE, null, cv);
}
my createNew() that is executed to make new tables
public void createNew(SQLiteDatabase db, String TABLE_NAME){
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_QUESTION + " TEXT NOT NULL, " +
KEY_PATH + " TEXT NOT NULL);"
);
}
last but not lease, my logcat:
11-25 22:02:30.418: I/SqliteDatabaseCpp(24726): sqlite returned: error code = 1, msg = near "helloDB": syntax error
11-25 22:02:30.428: D/AndroidRuntime(24726): Shutting down VM
11-25 22:02:30.428: W/dalvikvm(24726): threadid=1: thread exiting with uncaught exception (group=0x40ab9228)
11-25 22:02:30.438: E/AndroidRuntime(24726): FATAL EXCEPTION: main
11-25 22:02:30.438: E/AndroidRuntime(24726): android.database.sqlite.SQLiteException: near "helloDB": syntax error: , while compiling: CREATE TABLE hello helloDB (_id INTEGER PRIMARY KEY AUTOINCREMENT, question TEXT NOT NULL, path TEXT NOT NULL);
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:141)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:368)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteStatement.acquireAndLock(SQLiteStatement.java:272)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:84)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:2031)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1971)
11-25 22:02:30.438: E/AndroidRuntime(24726): at com.mitterederStudios.Quiz.Table$DbHelper.createNew(Table.java:49)
11-25 22:02:30.438: E/AndroidRuntime(24726): at com.mitterederStudios.Quiz.Table.createNew(Table.java:94)
11-25 22:02:30.438: E/AndroidRuntime(24726): at com.mitterederStudios.Quiz.Menu$1.onClick(Menu.java:56)
11-25 22:02:30.438: E/AndroidRuntime(24726): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:174)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.os.Handler.dispatchMessage(Handler.java:99)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.os.Looper.loop(Looper.java:154)
11-25 22:02:30.438: E/AndroidRuntime(24726): at android.app.ActivityThread.main(ActivityThread.java:4945)
11-25 22:02:30.438: E/AndroidRuntime(24726): at java.lang.reflect.Method.invokeNative(Native Method)
11-25 22:02:30.438: E/AndroidRuntime(24726): at java.lang.reflect.Method.invoke(Method.java:511)
11-25 22:02:30.438: E/AndroidRuntime(24726): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-25 22:02:30.438: E/AndroidRuntime(24726): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-25 22:02:30.438: E/AndroidRuntime(24726): at dalvik.system.NativeStart.main(Native Method)
You need to put quotes around your table name so its "test 1" if you really want spaces. However this is generally a bad idea, I would replace the spaces with underscores so it becomes test_1.

Categories