try catch - Unable to instantiate activity ComponentInfo - java

I have two methods to update and delete data in my app, I have implemeted try catches within my switch statement and am now getting the following error:
01-14 20:38:58.778: D/AndroidRuntime(273): Shutting down VM
01-14 20:38:58.778: W/dalvikvm(273): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-14 20:38:58.798: E/AndroidRuntime(273): FATAL EXCEPTION: main
01-14 20:38:58.798: E/AndroidRuntime(273): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.flybase2/com.example.flybase2.viewEdit}: java.lang.NullPointerException
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.os.Looper.loop(Looper.java:123)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.reflect.Method.invoke(Method.java:521)
01-14 20:38:58.798: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-14 20:38:58.798: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-14 20:38:58.798: E/AndroidRuntime(273): at dalvik.system.NativeStart.main(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): Caused by: java.lang.NullPointerException
01-14 20:38:58.798: E/AndroidRuntime(273): at com.example.flybase2.viewEdit.<init>(viewEdit.java:63)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.Class.newInstanceImpl(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.Class.newInstance(Class.java:1429)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
01-14 20:38:58.798: E/AndroidRuntime(273): ... 11 more
Can anyone see the issue? It works perfectly without the try catches.
Heres the class:
package com.example.flybase2;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class viewEdit extends Activity implements OnClickListener{
EditText namePassedEdit;
EditText numPassedEdit;
EditText emailPassedEdit;
EditText commentPassedEdit;
Button bUpdate;
Button bDelete;
long passedID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editview);
DBHandler displayEdit = new DBHandler(this, null, null);
Bundle extras = getIntent().getExtras();
if (extras != null) {
passedID = extras.getLong("passedID");
}
displayEdit.open();
String returnedNameToEdit = displayEdit.getName(passedID);
String returnedNumToEdit = displayEdit.getNum(passedID);
String returnedEmailToEdit = displayEdit.getEmail(passedID);
String returnedCommentToEdit = displayEdit.getComments(passedID);
namePassedEdit = (EditText) findViewById(R.id.inputNameEdit);
numPassedEdit = (EditText) findViewById(R.id.inputTelNoEdit);
emailPassedEdit = (EditText) findViewById(R.id.inputEmailEdit);
commentPassedEdit = (EditText) findViewById(R.id.inputCommentEdit);
bUpdate = (Button) findViewById (R.id.btnAddConEdit);
bDelete = (Button) findViewById (R.id.btnDeleteContact);
namePassedEdit.setText(returnedNameToEdit);
numPassedEdit.setText(returnedNumToEdit);
emailPassedEdit.setText(returnedEmailToEdit);
commentPassedEdit.setText(returnedCommentToEdit);
bUpdate.setOnClickListener(this);
bDelete.setOnClickListener(this);
}
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
#Override
public void onClick(View updateOrDeleteClicked) {
boolean check = true;
switch(updateOrDeleteClicked.getId()){
case (R.id.btnAddConEdit):
try
{
DBHandler updateData = new DBHandler(this, null, null);
updateData.open();
updateData.updateData(passedID, nameEdit, telEdit, emailEdit, commentEdit);
}
catch (Exception e)
{
check = false;
Dialog d = new Dialog(this);
d.setTitle("Contact failed to be deleted.");
TextView txt = new TextView(this);
txt.setText("Fail");
d.setContentView(txt);
d.show();
}
finally
{
if(check = true);
{
Dialog e = new Dialog(this);
e.setTitle("Contact deleted.");
TextView txt = new TextView(this);
txt.setText("Success");
e.setContentView(txt);
e.show();
}
}
break;
case (R.id.btnDeleteContact):
try
{
DBHandler deleteContact = new DBHandler(this, null, null);
deleteContact.open();
deleteContact.deleteData(passedID);
}
catch (Exception e)
{
check = false;
Dialog d = new Dialog(this);
d.setTitle("Contact failed to be deleted.");
TextView txt = new TextView(this);
txt.setText("Fail");
d.setContentView(txt);
d.show();
}
finally
{
if(check = true);
{
Dialog e = new Dialog(this);
e.setTitle("Contact deleted.");
TextView txt = new TextView(this);
txt.setText("Success");
e.setContentView(txt);
e.show();
}
}
break;
}
}
}

String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
These lines aren't inside a method, and you can't use them like that. You're getting a null pointer on namePassedEdit because it's trying to initialize them when the class is created, and they aren't assigned anything yet.

One issue I see here is:
if(check = true); //This ends if statement here and here you are assigning true to check nothing more than that..
I guess what you need here is:
if(check){....}

The main problem I can find is that you close the braces for your onCreate on line 59. Leaving the following lines between functions.
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
If you move these up into the onCreate it will probably fix your issue. Also as #Nambari said in their answer, in your if statements you are checking if check was set to true. You need to change this to:
if(check)

Related

Debugging AsyncTask - strange behaviour, debug jumping into the code

I'm debugging an Asynctask that simply downloads a file: here the code:
public class AsyncDownloadFilesTask extends AsyncTask<String, Integer, Boolean> {
public AsyncResponse<Boolean> delegate=null;
protected Boolean doInBackground(String... params) {
android.os.Debug.waitForDebugger();
try {
URL url = new URL(params[0]);
int count;
String fileName = new String(params[1]);
URLConnection connessione = url.openConnection();
connessione.connect();
int lenghtOfFile = connessione.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(fileName);
long total = 0;
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
return Boolean.valueOf(true);
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(Boolean result) {
delegate.processFinish(result);
}
}
I obtain a strange behaviour: when execution arrive to return
Boolean.valueOf(true);
it skips to
return null;
into the catch block, but Exception e is null, and then debugger goto line 1 of AsyncTask, that is simply
package com.example.compa.asynctasks;
Then execution goes on (executing onPostExecute method) and, of course, returned result is null
What happens? Why debug jump in this way?
Task download correctly the file.
Here code of the Activity that instantiates and calls Async Task
package com.example.compa.activities;
import android.app.Activity;
import ...
public class CoverActivity extends Activity implements AsyncResponse<Boolean>{
ImageView coverImg;
Drawable d;
CompassesFileManager cfm;
int coverId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cover);
coverId = getIntent().getExtras().getInt("coverId");
cfm = new CompassesFileManager(this);
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
d = cfm.getCover(coverId);
if (d!=null){
coverImg.setImageDrawable(d);
} else {
AsyncDownloadFilesTask task = new AsyncDownloadFilesTask();
task.delegate = this;
task.execute(cfm.getCoverURL(coverId), cfm.getCoverFileName(coverId));
}
}
#Override
public void processFinish(Boolean output) {
if (output){
Drawable d = cfm.getCover(coverId);
coverImg.setImageDrawable(d);
} else {
finish();
}
}
}
Stacktrace of error:
02-21 19:37:29.520: E/AndroidRuntime(407): FATAL EXCEPTION: main
02-21 19:37:29.520: E/AndroidRuntime(407): java.lang.NullPointerException
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:1)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.finish(AsyncTask.java:631)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Looper.loop(Looper.java:176)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.app.ActivityThread.main(ActivityThread.java:5419)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invoke(Method.java:525)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
02-21 19:37:29.520: E/AndroidRuntime(407): at dalvik.system.NativeStart.main(Native Method)
line:
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
is the last one of AsyncDownloadFilesTask class, and is a closing bracket, }
Thank you
I don't have enough points to comment, but it looks like delegate is null in your onPostExecute
delegate.processFinish(result); // delegate is null
if that's not the case, you're code stub above doesn't define it though.
I solved on my own.
1st, I move call to the Async Task in the onStart() method, instead of onCreate()
2nd, I made a mistake, in change line
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
in
coverImg = (ImageView)findViewById(R.id.cover_image);
to avoid a stupid null pointer (I already declared coverImg)!
Anyway, I still don't understand debug's behaviour, but I solved my problem.
Thank you everybody

Activity closes when trying to asyncronously connect to twitter

I have been trying to program a twitter client for Android (using twitter4j). So far the idea is to have a simple GUI, and if there is not a file with the OAuth token in the SD Card, connect to the Twitter API using AsyncTask, get the URL for the authorization and open the default browser. However, the browser never runs. Depending on the different modifications I have made trying to fix this, either the Activity starts normally but the browser never starts or the Activity crashes. I have come to a point of a a little of frustation and confussion. Can someone point out what's wrong with my code?
public class StatusActivity extends Activity {
private static final String TAG = "StatusActivity";
EditText editText;
Button updateButton;
File oauthfile = null;
public Context context = getApplicationContext();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
Log.d(TAG, "started");
// Find views
editText = (EditText) findViewById(R.id.editText); //
updateButton = (Button) findViewById(R.id.buttonUpdate);
oauthfile = new File("sdcard/auth_file.txt");
//Check if the file with the keys exist
if (oauthfile.exists()==false){
Log.d(TAG, "file not created");
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "file not created.", Toast.LENGTH_SHORT);
toast.show();
new Authorization(context).execute();
}
}
public void openBrowser (View v){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
Log.d(TAG, "onclick");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.status, menu);
return true;
}
}
class Authorization extends AsyncTask <String, Integer, String>{
String url = null;
private Context context;
Authorization(Context context) {
this.context = context.getApplicationContext();
}
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Invoke onPreExecute()", Toast.LENGTH_SHORT).show();
}
#Override
public String doInBackground(String... params) {
ConfigurationBuilder configBuilder = new ConfigurationBuilder();
configBuilder.setDebugEnabled(true)
//I have eliminated the keys from the question :)
.setOAuthConsumerKey("XXXXXXXXXXXXXX")
.setOAuthConsumerSecret("XXXXXXXXXXXXXXX");
Twitter OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
RequestToken requestToken = null;
AccessToken accessToken = null;
do{
try {
requestToken = OAuthTwitter.getOAuthRequestToken();
url = requestToken.getAuthorizationURL();
}
catch (TwitterException ex) {
ex.printStackTrace();
}
}
while (accessToken==null);
return url;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(context, "Opening browser.", Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_ALL_APPS, Uri.parse(url));
context.startActivity(browserIntent);
}
}
I know that at least checks if the file for the tokens exists because the toast "file not created" appears, and that the activity is able to run the browser if I press the button. The app has permissions to write in the SD card and use the Internet. Thanks in advance.
Logcat Trace:
03-28 19:02:32.816: E/AndroidRuntime(278): FATAL EXCEPTION: main
03-28 19:02:32.816: E/AndroidRuntime(278): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.versec.pardinus/com.versec.pardinus.StatusActivity}: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Looper.loop(Looper.java:123)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invoke(Method.java:521)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-28 19:02:32.816: E/AndroidRuntime(278): at dalvik.system.NativeStart.main(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): Caused by: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.versec.pardinus.StatusActivity.<init>(StatusActivity.java:30)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstanceImpl(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstance(Class.java:1429)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
03-28 19:02:32.816: E/AndroidRuntime(278): ... 11 more
This is what is causing your crash.
public Context context = getApplicationContext();
You're not even using it when you need it, so you can just get rid of this line.
Btw, something else I noticed while looking at your code is this:
oauthfile = new File("sdcard/auth_file.txt");
Don't take the "sdcard/" path for granted. Use this instead:
File dir = Environment.getExternalStorageDirectory();
File oauthfile = new File(dir, "auth_file.txt");

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.

Button click=unfortunately app has stopped

Hi im new to android programming and this code produces an error when the button is clicked... It shows unfortunately the application has stopped can anybody check? :(
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.compute);
aButton = (Button) this.findViewById(R.id.Button06);
//get intent
Intent i = getIntent();
Bundle extras = i.getExtras(); // get the parameters
density = getBaseContext().getResources().getDisplayMetrics().density;
int textViewSizeDp = (int)(200 * density);
int textFieldSizeDp = (int)(50 * density);
FieldsLayout = (LinearLayout) findViewById(R.id.FieldsLayout);
if(extras!=null){
items = (extras.getString("items")).split(",");
rows = new LinearLayout[items.length];
labels = new TextView[items.length];
fields = new EditText[items.length];
for (int ctr=0;ctr<items.length;ctr++){
rows[ctr] = new LinearLayout(Compute.this);
rows[ctr].setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
rows[ctr].setOrientation(LinearLayout.HORIZONTAL);
rows[ctr].setLayoutParams(new LayoutParams (LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
FieldsLayout.addView(rows[ctr]);
labels[ctr] = new TextView(Compute.this);
labels[ctr].setText(items[ctr]);
labels[ctr].setMinimumWidth(textViewSizeDp);
rows[ctr].addView(labels[ctr]);
fields[ctr] = new EditText(Compute.this);
fields[ctr].setMinimumWidth(textFieldSizeDp);
rows[ctr].addView(fields[ctr]);
}
}
else{
finish();
}
aButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Compute.this, Total.class);
//I believe this causes the error
for(int ctr=0;ctr<fields.length;ctr++){
itemName[ctr] = labels[ctr].getText().toString();
}
for(int ctr=0;ctr<fields.length;ctr++){
itemHour[ctr] = Integer.parseInt(fields[ctr].getText().toString());
}
//until here
i.putExtra("hours",itemHour);
i.putExtra("items",itemName);
startActivity(i);
}});
}
here's the error log: (or is this it?)
01-14 09:37:16.047: W/Trace(768): Unexpected value from nativeGetEnabledTags: 0
01-14 09:37:16.187: E/AndroidRuntime(768): FATAL EXCEPTION: main
01-14 09:37:16.187: E/AndroidRuntime(768): java.lang.NullPointerException
01-14 09:37:16.187: E/AndroidRuntime(768): at com.example.mpc.Compute$1.onClick(Compute.java:82)
01-14 09:37:16.187: E/AndroidRuntime(768): at android.view.View.performClick(View.java:4202)
01-14 09:37:16.187: E/AndroidRuntime(768): at android.view.View$PerformClick.run(View.java:17340)
01-14 09:37:16.187: E/AndroidRuntime(768): at android.os.Handler.handleCallback(Handler.java:725)
01-14 09:37:16.187: E/AndroidRuntime(768): at android.os.Handler.dispatchMessage(Handler.java:92)
01-14 09:37:16.187: E/AndroidRuntime(768): at android.os.Looper.loop(Looper.java:137)
01-14 09:37:16.187: E/AndroidRuntime(768): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-14 09:37:16.187: E/AndroidRuntime(768): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 09:37:16.187: E/AndroidRuntime(768): at java.lang.reflect.Method.invoke(Method.java:511)
01-14 09:37:16.187: E/AndroidRuntime(768): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-14 09:37:16.187: E/AndroidRuntime(768): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-14 09:37:16.187: E/AndroidRuntime(768): at dalvik.system.NativeStart.main(Native Method)
Check out following things:
Make sure your field array is initialized properly.
Make sure that the length of itemName is same as that of fields.length and it should be properly initialized.
Make sure that the length of labels is same as that of fields.length and it should be properly initialized.
Make sure that the length of itemHour is same as that of fields.length and it should be properly initialized.
Check the following:
The Id of button
Same id more then one button in same layout.
Its map with xml file or not.
As this is NullPointerException, you are either having some null fields or you have forgotten to initialise some of your fields,
Check,
If you have done aButton = (Button)findViewById(R.id.ButtonID);
if you have initialised itemName[] and itemHour[], something like itemHour[ctr] = new String[];
If there are any values in the labels[] and fields[]
If it still doesnt helps, then you should post some more relavent code, only then I could edit my answer.

If condition causing program to force close

I am doing an android app and i was thinking of creating a theme option. Well all I was thinking of doing was to allow the user to click on a image button which represented a theme. And when he clicks on it I start a new activity i.e i direct him to the home page. Also i have created a few integer variables which are set to 1 when the user clicks on a button.
Then in the other classes all i do is check if the variables are 1 or not and depending on that i apply the theme. By theme i mean i just change the background wallpaper. But this is not working. I mean the code works but if use an if loop to check the variable values and then apply the effects it causes an error.
Here's the complete code:
package com.example.themetest;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends Activity implements OnClickListener{
ImageButton ib1;
ImageButton ib2;
int water=0;
int fire=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ib1 = (ImageButton) findViewById(R.id.imageButton1);
ib2 = (ImageButton) findViewById(R.id.imageButton2);
ib1.setOnClickListener(this);
ib2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.imageButton1:
water = 1;
Intent wi = new Intent("com.example.themetest.THEME");
startActivity(wi);
break;
case R.id.imageButton2:
fire = 1;
Intent fi = new Intent("com.example.themetest.THEME");
startActivity(fi);
break;
}
}
}
Here's the other class where i check which variable is set to 1 and apply the effect.
package com.example.themetest;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.LinearLayout;
public class Theme extends Activity{
MainActivity main;
Resources res;
Drawable drawable;
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.theme);
if(main.water==1){
res = getResources();
drawable = res.getDrawable(R.drawable.water_theme);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
else if(main.fire==1){
res = getResources();
drawable = res.getDrawable(R.drawable.fire_theme);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
else{
res = getResources();
drawable = res.getDrawable(R.drawable.ic_launcher);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
}
}
I can change the wallpaper without using the if loop, but i want to do it this way which is not working. Can anyone please tell me why?
Log cat:
01-15 12:08:23.339: D/dalvikvm(273): GC_EXTERNAL_ALLOC freed 767 objects / 55936 bytes in 235ms
01-15 12:08:25.539: D/AndroidRuntime(273): Shutting down VM
01-15 12:08:25.539: W/dalvikvm(273): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-15 12:08:25.559: E/AndroidRuntime(273): FATAL EXCEPTION: main
01-15 12:08:25.559: E/AndroidRuntime(273): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.themetest/com.example.themetest.Theme}: java.lang.NullPointerException
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.os.Handler.dispatchMessage(Handler.java:99)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.os.Looper.loop(Looper.java:123)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-15 12:08:25.559: E/AndroidRuntime(273): at java.lang.reflect.Method.invokeNative(Native Method)
01-15 12:08:25.559: E/AndroidRuntime(273): at java.lang.reflect.Method.invoke(Method.java:521)
01-15 12:08:25.559: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-15 12:08:25.559: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-15 12:08:25.559: E/AndroidRuntime(273): at dalvik.system.NativeStart.main(Native Method)
01-15 12:08:25.559: E/AndroidRuntime(273): Caused by: java.lang.NullPointerException
01-15 12:08:25.559: E/AndroidRuntime(273): at com.example.themetest.Theme.onCreate(Theme.java:29)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-15 12:08:25.559: E/AndroidRuntime(273): ... 11 more
01-15 12:08:31.089: I/Process(273): Sending signal. PID: 273 SIG: 9
I think the better way to do this is pass the name or code of the theme user selected along with the intent.
This might help: Passing data through Intent and receiving it
You cannot access other activities variables this way, a better way (for example) is to use a constant class..
public class Constants {
public static int water=0;
public staticint fire=0;
}
MainActivity:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.imageButton1:
Constants.water = 1;
Intent wi = new Intent("com.example.themetest.THEME");
startActivity(wi);
break;
case R.id.imageButton2:
Constants.fire = 1;
Intent fi = new Intent("com.example.themetest.THEME");
startActivity(fi);
break;
}
}
Theme:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.theme);
if(Constants.water==1){
res = getResources();
drawable = res.getDrawable(R.drawable.water_theme);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
else if(Constants.fire==1){
res = getResources();
drawable = res.getDrawable(R.drawable.fire_theme);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
else{
res = getResources();
drawable = res.getDrawable(R.drawable.ic_launcher);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
}

Categories