The code runs and my emails send, but anytime I check a box the subject is not altered because the method setSubject() is not called. Got it. Where I'm having trouble is where would I call/place this method so I can use the subject in my doInBackground() method. If I try calling setSubject() right before or anywhere in doInBackground I get an error for running concurrent tasks on the same thread. I tried calling setSubject() in a onPreExecute() block and still got the error. Anybody have any ideas? Here is the code and LogCat.
public class lastpage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lastpage);
}
//method to verify email format using regex pattern
public boolean validateEmail(String email) {
Pattern pattern;
Matcher matcher;
//set variable to regex email pattern
final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
if (matcher.matches()) {
return true;
}
return false;
}
public void sendEmails() {
AsyncTask<String, Void, Void> myTask = new AsyncTask<String, Void, Void>() {
private String sub = "Maintenance Request";
String s = "";
CheckBox main = (CheckBox) findViewById(R.id.checkBox1);
CheckBox kitchen = (CheckBox) findViewById(R.id.checkBox2);
CheckBox bathroom = (CheckBox) findViewById(R.id.checkBox3);
CheckBox other = (CheckBox) findViewById(R.id.checkBox4);
public String setSubject(String subject) {
sub = subject;
if (main.isChecked()) subject = subject + " - Main Room";
if (kitchen.isChecked()) subject = subject + " - Kitchen";
if (bathroom.isChecked()) subject = subject + " - Bathroom";
if (other.isChecked()) subject = subject + " - Other";
return subject;
}
s = setSubject(sub);
protected Void doInBackground(String... params) {
String host = "smtp.gmail.com";
String username = "user#gmail.com";
String password = "pwd";
Properties props = new Properties();
props.put("mail.smtp.ssl.enable", "true");
Session session = Session.getInstance(props);
session.setDebug(true);
EditText e = (EditText) findViewById(R.id.enterEmail);
EditText g = (EditText) findViewById(R.id.whichApt);
String f = e.toString().replace("\\s", "");
String to = "to#yahoo.com";
String manager = "manager#gmail.com";
String subject1 = "Maintenance Confirmation";
MimeMessage msg = new MimeMessage(session);
MimeMessage msg1 = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(username));
msg1.setFrom(new InternetAddress(username));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
msg1.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(manager));
msg.setSubject(subject1);
msg1.setSubject(s);
msg.setText("Some really important stuff. Confirmed.");
msg1.setText("Really important stuff needs attention");
props.put("mail.smtps.auth", "true");
props.put("mail.smtp.quitwait", "false");
Transport t = session.getTransport("smtps");
try {
t.connect(host, username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.sendMessage(msg1, msg1.getAllRecipients());
}
finally {
t.close();
} }
catch(Exception exc){
exc.printStackTrace();
}
return null;
}};
myTask.execute(); }
//method to run when button is clicked
public void buttonclick3(View v) {
//first extract text for EditText and convert to String
EditText e = (EditText) findViewById(R.id.enterEmail);
String email = e.getText().toString();
//run validateEmail on String and show alert if format is invalid
if (validateEmail(email) == false) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please enter a valid Email address.");
builder.setTitle("Invalid Input!");
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.show();
}
else {
sendEmails();
}
}
}
Here is the LogCat I get when I try calling setSubject() anywhere.
- 04-14 17:52:09.091: W/dalvikvm(1510): threadid=1: thread exiting with
uncaught exception (group=0x41bbaa08)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): FATAL EXCEPTION: main
- 04-14 17:52:09.101: E/AndroidRuntime(1510): java.lang.IllegalStateException: Could not execute method of the activity
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.view.View$1.onClick(View.java:3626)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.view.View.performClick(View.java:4231)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.view.View$PerformClick.run(View.java:17537)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.os.Handler.handleCallback(Handler.java:725)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.os.Handler.dispatchMessage(Handler.java:92)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.os.Looper.loop(Looper.java:158)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.app.ActivityThread.main(ActivityThread.java:5751)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at java.lang.reflect.Method.invokeNative(Native Method)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at java.lang.reflect.Method.invoke(Method.java:511)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at dalvik.system.NativeStart.main(Native Method)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): Caused by: java.lang.reflect.InvocationTargetException
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at java.lang.reflect.Method.invokeNative(Native Method)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at java.lang.reflect.Method.invoke(Method.java:511)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.view.View$1.onClick(View.java:3621)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): ... 11 more
- 04-14 17:52:09.101: E/AndroidRuntime(1510): Caused by: java.lang.NullPointerException
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.example.maintenanceapp.lastpage$1.setSubject(lastpage.java:81)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.example.maintenanceapp.lastpage$1.<init>(lastpage.java:87)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.example.maintenanceapp.lastpage.sendEmails(lastpage.java:72)
Don't try to find checkboxes on a different activity. Instead, send the information needed in the Intent used to start the next activity.
Related
I'm trying to add some values to my database from my android application through JSON.
I have used the below code previously with eclipse and worked perfectly, now im trying it using android studio and it isn't working I don't know why!
code:
public class Main2Activity extends AppCompatActivity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText ID;
EditText fname;
EditText lname;
EditText phone;
Button addbtn;
// url to create new product
private static String url_create_product = "http://www.lamia.byethost18.com/add_info.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
String H,Q,C,Ls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ID = (EditText) findViewById(R.id.ID);
lname = (EditText) findViewById(R.id.lname);
fname = (EditText) findViewById(R.id.fname);
phone = (EditText) findViewById(R.id.phone);
H = ID.getText().toString();
Q = lname.getText().toString();
C = fname.getText().toString();
Ls = phone.getText().toString();
addbtn = (Button) findViewById(R.id.addbtn);
addbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
new CreateNewProduct().execute();
}
});
}
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Main2Activity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("ID", H));
params.add(new BasicNameValuePair("lname", Q));
params.add(new BasicNameValuePair("fname", C));
params.add(new BasicNameValuePair("phone", Ls));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
// Intent i = new Intent(getApplicationContext(), AdminExercise.class);
// startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
I got this error:
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/JSON Parser: Error parsing data org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONObject
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: Process: com.example.hatim.maps, PID: 1934
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: java.lang.RuntimeException: An error occurred while executing doInBackground()
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:309)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:242)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at com.example.hatim.maps.Main2Activity$CreateNewProduct.doInBackground(Main2Activity.java:113)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at com.example.hatim.maps.Main2Activity$CreateNewProduct.doInBackground(Main2Activity.java:77)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:295)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
I don't get what is the error?
can someone help please? thank you!
It seems that your request is not receiving a JSON, may be is an HTML error because the value received starts with html format:
E/JSON Parser: Error parsing data org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONObject
I am new to android. I have created an app which was a pull parser in order to extract items from an Rss feed, into a ListView. Unfortunately my app seems to force close when I try and place code in order implement some sort of filtering mechanism in my ListView. This is the code I have so far, and I have no idea why it seems to crash. Any help would be appreciated.
public class RssFeed extends ListActivity {
// Listview Adapter
ArrayAdapter<string> adapter;
EditText SearchBox;
List titles;
public static List description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rss);
// Initialising instance variables
titles = new ArrayList();
description = new ArrayList();
try {
URL url = new URL("http://my.url");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
/** While the rss feed has not displayed end_document, pull the title and description information */
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
titles.add(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("description")) {
if (insideItem)
description.add(xpp.nextText());
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, titles);
setListAdapter(adapter);
/**
* Enabling Search Filter
* */
SearchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
RssFeed.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
}
And the LogCat:
04-12 20:43:00.792: D/dalvikvm(324): GC freed 7597 objects / 316440 bytes in 88ms
04-12 20:43:00.852: D/AndroidRuntime(324): Shutting down VM
04-12 20:43:00.852: W/dalvikvm(324): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
04-12 20:43:00.852: E/AndroidRuntime(324): Uncaught handler: thread main exiting due to uncaught exception
04-12 20:43:00.862: E/AndroidRuntime(324): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.me.myandroidstuff.simpleRssReader/org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed}: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Looper.loop(Looper.java:123)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.main(ActivityThread.java:4363)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invokeNative(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invoke(Method.java:521)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-12 20:43:00.862: E/AndroidRuntime(324): at dalvik.system.NativeStart.main(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): Caused by: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed.onCreate(RssFeed.java:142)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
04-12 20:43:00.862: E/AndroidRuntime(324): ... 11 more
04-12 20:43:00.892: I/dalvikvm(324): threadid=7: reacting to signal 3
04-12 20:43:00.892: E/dalvikvm(324): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
First of all: the class you posted doesn't have 142 lines, be sure to post the whole class.
Second: SearchBox is null here.
That is because you declared it with
EditText SearchBox;
but never assigned it which you would usually do from your layout like
SearchBox = (EditText) findViewById(R.id.searchBox);
(just an example)
SeachBox does not have an assigned value at this point so you can't use any methods on it.
Third: Use lower case names like searchBox, it'll make your code easier to read for others and yourself.
public class MainActivity extends Activity implements View.OnClickListener {
int i, j, butNum, lay1num = 1, lay2num = 100, lay3num = 100, store;
Button[] Button;
EditText numBut;
LinearLayout mainLayout;
LinearLayout[] subLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
butNum = 5;
Button = new Button[butNum];
subLayout = new LinearLayout[3];
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.HORIZONTAL);
mainLayout.setWeightSum(90);
mainLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
subLayout[0] = new LinearLayout(this);
subLayout[0].setOrientation(LinearLayout.VERTICAL);
subLayout[0].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 30));
subLayout[0].setGravity(Gravity.CENTER_HORIZONTAL);
subLayout[1] = new LinearLayout(this);
subLayout[1].setOrientation(LinearLayout.VERTICAL);
subLayout[1].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 30));
subLayout[2] = new LinearLayout(this);
subLayout[2].setOrientation(LinearLayout.VERTICAL);
subLayout[2].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 30));
subLayout[0].setGravity(0x10);
for (i = 0; i < 3; i++) {
for (j = 0; j < butNum; j++) {
int value = j + 1;
Button[j] = new Button(this);
Button[j].setText("" + value);
Button[j].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Button[j].setTextSize(20);
Button[j].setWidth(100 + j * 20);
Button[j].setTag(value);
Button[j].setId(j);
subLayout[i].addView(Button[j]);
Button[j].setOnClickListener(this);
}
}
TextView text = new TextView(this);
text.setText("" + store);
subLayout[0].addView(text);
mainLayout.addView(subLayout[0]);
mainLayout.addView(subLayout[1]);
mainLayout.addView(subLayout[2]);
setContentView(mainLayout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onClick(View v) {
// TODO Auto-generated method stub
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
switch (v.getId()) {
case 0:
subLayout[0].addView(Button[0], layoutParams);
break;
}
}
}
I created three layouts using java and added them to a mainlayout. I added buttons to the first layout when activity starts. What I want to do is to add a new Button to subLayout[1] when we click on a button.But when I am running the program it crashes(saying the program has stopped unexpectedly) when I click on button.The LogCat is :
04-14 03:52:39.174: D/AndroidRuntime(349): Shutting down VM
04-14 03:52:39.174: W/dalvikvm(349): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-14 03:52:39.184: E/AndroidRuntime(349): FATAL EXCEPTION: main
04-14 03:52:39.184: E/AndroidRuntime(349): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
04-14 03:52:39.184: E/AndroidRuntime(349): at android.view.ViewGroup.addViewInner(ViewGroup.java:1970)
04-14 03:52:39.184: E/AndroidRuntime(349): at android.view.ViewGroup.addView(ViewGroup.java:1865)
04-14 03:52:39.184: E/AndroidRuntime(349): at android.view.ViewGroup.addView(ViewGroup.java:1845)
04-14 03:52:39.184: E/AndroidRuntime(349): at com.creos.towerofhanoi.MainActivity.onClick(MainActivity.java:85)
04-14 03:52:39.184: E/AndroidRuntime(349): at android.view.View.performClick(View.java:2408)
04-14 03:52:39.184: E/AndroidRuntime(349): at android.view.View$PerformClick.run(View.java:8816)
04-14 03:52:39.184: E/AndroidRuntime(349): at android.os.Handler.handleCallback(Handler.java:587)
04-14 03:52:39.184: E/AndroidRuntime(349): at android.os.Handler.dispatchMessage(Handler.java:92)
04-14 03:52:39.184: E/AndroidRuntime(349): at android.os.Looper.loop(Looper.java:123)
04-14 03:52:39.184: E/AndroidRuntime(349): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-14 03:52:39.184: E/AndroidRuntime(349): at java.lang.reflect.Method.invokeNative(Native Method)
04-14 03:52:39.184: E/AndroidRuntime(349): at java.lang.reflect.Method.invoke(Method.java:521)
04-14 03:52:39.184: E/AndroidRuntime(349): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-14 03:52:39.184: E/AndroidRuntime(349): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-14 03:52:39.184: E/AndroidRuntime(349): at dalvik.system.NativeStart.main(Native Method)
I solved it at last I had to specify the button parameters inside the onclick. It was a small mistake
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case 0:
Button[0] = new Button(this);
Button[0].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
subLayout[1].addView(Button[0]);
break;
}
}
In my android application the data has to be shared using twitter so had followed this link http://androidcodeexamples.blogspot.in/2011/12/how-to-integrate-twitter-in-android.html, everything works fine, but after giving username and password, getting force close option.
here's the logcat output
01-17 17:07:54.118: E/AndroidRuntime(383): FATAL EXCEPTION: main
01-17 17:07:54.118: E/AndroidRuntime(383): java.lang.NullPointerException
01-17 17:07:54.118: E/AndroidRuntime(383): com.twitter.android.TwitterApp$1.handleMessage(TwitterApp.java:237)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.os.Handler.dispatchMessage(Handler.java:99)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.os.Looper.loop(Looper.java:123)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.app.ActivityThread.main(ActivityThread.java:3683)
01-17 17:07:54.118: E/AndroidRuntime(383): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 17:07:54.118: E/AndroidRuntime(383): at java.lang.reflect.Method.invoke(Method.java:507)
01-17 17:07:54.118: E/AndroidRuntime(383): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-17 17:07:54.118: E/AndroidRuntime(383): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-17 17:07:54.118: E/AndroidRuntime(383): at dalvik.system.NativeStart.main(Native Method)
this is the code in mainactivity
public class Singlemenuitem extends Activity {
private TwitterApp mTwitter;
private static final String CONSUMER_KEY = "6JyIkj71ZqG4wk3YF0Y4hw";
private static final String CONSUMER_SECRET = "sJl9aRVqlEt7nxlKvpMVK6tLULz5FSQ2KUOW0yie4";
private enum FROM {
TWITTER_POST, TWITTER_LOGIN
};
private enum MESSAGE {
SUCCESS, DUPLICATE, FAILED, CANCELLED
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mTwitter = new TwitterApp(this, CONSUMER_KEY, CONSUMER_SECRET);
//share twitter
final ImageView twitter = (ImageView) findViewById(R.id.twitter);
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
mTwitter.resetAccessToken();
if (mTwitter.hasAccessToken() == true) {
try {
mTwitter.updateStatus(String.valueOf(Html
.fromHtml(TwitterApp.MESSAGE)));
// File f = new File("/mnt/sdcard/android.jpg");
// mTwitter.uploadPic(f, String.valueOf(Html
// .fromHtml(TwitterApp.MESSAGE)));
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
} else {
mTwitter.authorize();
}
}
private void postAsToast(FROM twitterPost, MESSAGE success) {
switch (twitterPost) {
case TWITTER_LOGIN:
switch (success) {
case SUCCESS:
Toast.makeText(Singlemenuitem.this, "Login Successful", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(Singlemenuitem.this, "Login Failed", Toast.LENGTH_LONG).show();
default:
break;
}
break;
case TWITTER_POST:
switch (success) {
case SUCCESS:
Toast.makeText(Singlemenuitem.this, "Posted Successfully", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(Singlemenuitem.this, "Posting Failed", Toast.LENGTH_LONG)
.show();
break;
case DUPLICATE:
Toast.makeText(Singlemenuitem.this,
"Posting Failed because of duplicate message...",
Toast.LENGTH_LONG).show();
default:
break;
}
break;
}
TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
public void onError(String value) {
postAsToast(FROM.TWITTER_LOGIN, MESSAGE.FAILED);
Log.e("TWITTER", value);
mTwitter.resetAccessToken();
}
public void onComplete(String value) {
try {
mTwitter.updateStatus(TwitterApp.MESSAGE);
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
}
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.