I have been working on a preferences screen for an app, and I haven't even gotten it to display the screen before it crashes. I have examined several tutorials about shared preferences and my code resembles theirs, but nothing has worked. I think the problem is in my preferences.xml file, because I commented out everything except the opening of the XML file in my PreferenceActivity.
Here is my preferences.xml file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Password">
<EditTextPreference
android:name="Your Password"
android:title="Password"
android:defaultValue=""
android:summary="For logging in if facial recognition fails"
android:key="password" />
<EditTextPreference
android:name="Max Attempts"
android:title="Max Attempts"
android:defaultValue="3"
android:summary="Max number of times to try authentication before falling back to password"
android:key="maxAttempts" />
</PreferenceCategory>
<PreferenceCategory
android:title="Security">
<CheckBoxPreference
android:title="Intruder Alert"
android:defaultValue="false"
android:summary="Notify me if you detect a face other than mine"
android:key="intruderAlert" />
</PreferenceCategory>
<PreferenceCategory
android:title="Intruder Notification">
<EditTextPreference
android:name="Your Email"
android:title="email"
android:defaultValue=""
android:summary="An email address for us to notify"
android:key="email" />
<EditTextPreference
android:name="Your Phone Number"
android:title="phoneNumber"
android:defaultValue=""
android:summary="A phone number for us to notify"
android:key="phoneNumber" />
</PreferenceCategory>
</PreferenceScreen>
And, in case I'm wrong and my problem is my java file, here's the PreferenceActivity. Most is commented out at the moment, but the program still crashes.
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
/*private EditTextPreference password;
private EditTextPreference maxAttempts;
private CheckBoxPreference intruderAlert;
private EditTextPreference email;
private EditTextPreference phoneNumber;
String PassWord;
int MaxAttempts;
boolean IntruderAlert;
String Email;
String PhoneNumber;*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
//password = (EditTextPreference) getPreferenceScreen().findPreference("password");
//maxAttempts = (EditTextPreference) getPreferenceScreen().findPreference("maxAttempts");
//intruderAlert = (CheckBoxPreference) getPreferenceScreen().findPreference("intruderAlert");
//email = (EditTextPreference) getPreferenceScreen().findPreference("email");
//phoneNumber = (EditTextPreference) getPreferenceScreen().findPreference("phoneNumber");
}
private void setSummaries()
{
}
#Override
protected void onResume()
{
/*super.onResume();
String intruderAlertSetting;
if (intruderAlert.isChecked())
intruderAlertSetting = "on";
else
intruderAlertSetting = "off";
password.setSummary("Your password is " +password.getText()+ ".");
maxAttempts.setSummary("The max attempts that will be made is "+maxAttempts.getText() + ".");
intruderAlert.setSummary("You have intruder alert set to" + intruderAlertSetting+".");
if (email.getText().equals(""))
email.setSummary("You have no email address stored.");
else
email.setSummary("Your stored email address is "+email.getText() + ".");
if (phoneNumber.getText().equals(""))
phoneNumber.setSummary("You have no phone number stored.");
else
phoneNumber.setSummary("Your stored phone number is " + phoneNumber.getText()+".");
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);*/
}
#Override
protected void onPause()
{
/*super.onPause();
String intruderAlertSetting;
if (intruderAlert.isChecked())
intruderAlertSetting = "on";
else
intruderAlertSetting = "off";
password.setSummary("Your password is " +password.getText()+ ".");
maxAttempts.setSummary("The max attempts that will be made is "+maxAttempts.getText() + ".");
intruderAlert.setSummary("You have intruder alert set to" + intruderAlertSetting+".");
if (email.getText().equals(""))
email.setSummary("You have no email address stored.");
else
email.setSummary("Your stored email address is "+email.getText() + ".");
if (phoneNumber.getText().equals(""))
phoneNumber.setSummary("You have no phone number stored.");
else
phoneNumber.setSummary("Your stored phone number is " + phoneNumber.getText()+".");
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);*/
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key)
{
/*String intruderAlertSetting;
if (intruderAlert.isChecked())
intruderAlertSetting = "on";
else
intruderAlertSetting = "off";
password.setSummary("Your password is " +password.getText()+ ".");
maxAttempts.setSummary("The max attempts that will be made is "+maxAttempts.getText() + ".");
intruderAlert.setSummary("You have intruder alert set to" + intruderAlertSetting+".");
if (email.getText().equals(""))
email.setSummary("You have no email address stored.");
else
email.setSummary("Your stored email address is "+email.getText() + ".");
if (phoneNumber.getText().equals(""))
phoneNumber.setSummary("You have no phone number stored.");
else
phoneNumber.setSummary("Your stored phone number is " + phoneNumber.getText()+".");
PassWord = password.getText();
MaxAttempts = Integer.parseInt(maxAttempts.getText());
IntruderAlert = intruderAlert.isChecked();
Email = email.getText();
PhoneNumber = phoneNumber.getText();*/
}
}
Here is the LogCat info on the crash:
04-23 16:37:09.181: WARN/dalvikvm(818): threadid=1: thread exiting with uncaught exception (group=0x40015560)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): FATAL EXCEPTION: main
04-23 16:37:09.221: ERROR/AndroidRuntime(818): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cs.fsu.edu.project4/com.cs.fsu.edu.project4.Preferences}: android.view.InflateException: Binary XML file line #2: Error inflating class PreferenceScreen
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1622)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.os.Handler.dispatchMessage(Handler.java:99)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.os.Looper.loop(Looper.java:123)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.app.ActivityThread.main(ActivityThread.java:3647)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at java.lang.reflect.Method.invokeNative(Native Method)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at java.lang.reflect.Method.invoke(Method.java:507)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at dalvik.system.NativeStart.main(Native Method)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class PreferenceScreen
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:581)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.view.LayoutInflater.inflate(LayoutInflater.java:386)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.app.Activity.setContentView(Activity.java:1657)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at com.cs.fsu.edu.project4.Preferences.onCreate(Preferences.java:33)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): ... 11 more
04-23 16:37:09.221: ERROR/AndroidRuntime(818): Caused by: java.lang.ClassNotFoundException: android.view.PreferenceScreen in loader dalvik.system.PathClassLoader[/data/app/com.cs.fsu.edu.project4-1.apk]
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.view.LayoutInflater.createView(LayoutInflater.java:471)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:549)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:66)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568)
04-23 16:37:09.221: ERROR/AndroidRuntime(818): ... 19 more
04-23 16:37:09.251: WARN/ActivityManager(62): Force finishing activity com.cs.fsu.edu.project4/.Preferences
Maybe you change your preference schema, try by removing old preferencies files stored in /dbdata/databases/com_your_app/shared_prefs/ or /data/data/com_your_app.
In your Preference Activity onCreate you probably had this:
setContentView(R.xml.prefs);
you need something like this instead:
addPreferencesFromResource(R.xml.prefs);
Refer to: PreferenceScreen class not found
Somehow the app thinks PreferenceScreen is of package android.view, but the system docs only knows it in package android.preference
Caused by: java.lang.ClassNotFoundException: android.view.PreferenceScreen in loader dalvik.system.PathClassLoader[/data/app/com.cs.fsu.edu.project4-1.apk]
Did you somehow add some class named PreferenceScreen in your app, which may confuse the system?
I'd like to add my cents here. My experience is, always make a clean build, always check your manifest for intents, activities, filters, permissions.
Check package names, sometimes you renamed packages which can go wrong.
Remove the previous app (created on differnt PC?) before installing, remove the old settings.
All this went wrong with me :-)
If this doesn't work, copy all files to a new project. Stupid, but this worked for me - uncommented everything, still didn't work. Then: ping, start & go.
Make sure you have the activity listed in the AndroidManifest.xml file
<activity android:name=".Preferences"></activity>
Related
I am trying to parse a value through intent while switching between activities.
I know I should read values from last intent with getExtra but I don't know why it doesn't work.
Also when I switch between activities on button click, application crashes.
In activity main I read text from editText and put it in Intent:
public void schimba(View view){
int value = Integer.parseInt(instances.getText().toString());;
Intent intent = new Intent(this, Tabel.class);
intent.putExtra("max", value);
startActivity(intent);
}
When it switch to activity 2 I have this:
Intent intentObject = getIntent();
int value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
value = intentObject.getIntExtra("max", 0);
/*
for(i=0;i<=value;i++)
{
LayoutInflater layoutinflate = null;
layoutinflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowview = layoutinflate.inflate( R.layout.activity_tabel, null);
}
*/
setContentView(R.layout.activity_tabel);
TextView showvalue;
showvalue = (TextView) findViewById(R.id.ShowValue);
showvalue.setText(""+value);
The idea is that I want to use this value in a for loop, I already know how to display the value in a textView but I don't need it, I wanna use it in for.
Logcat:
04-23 10:40:52.550: E/AndroidRuntime(1010): FATAL EXCEPTION: main
04-23 10:40:52.550: E/AndroidRuntime(1010): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.instances_temperature/com.example.instances_temperature.Tabel}: java.lang.NullPointerException
04-23 10:40:52.550: E/AndroidRuntime(1010): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-23 10:40:52.550: E/AndroidRuntime(1010): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-23 10:40:52.550: E/AndroidRuntime(1010): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-23 10:40:52.550: E/AndroidRuntime(1010): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-23 10:40:52.550: E/AndroidRuntime(1010): at android.os.Handler.dispatchMessage(Handler.java:99)
04-23 10:40:52.550: E/AndroidRuntime(1010): at android.os.Looper.loop(Looper.java:123)
04-23 10:40:52.550: E/AndroidRuntime(1010): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-23 10:40:52.550: E/AndroidRuntime(1010): at java.lang.reflect.Method.invokeNative(Native Method)
04-23 10:40:52.550: E/AndroidRuntime(1010): at java.lang.reflect.Method.invoke(Method.java:521)
04-23 10:40:52.550: E/AndroidRuntime(1010): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-23 10:40:52.550: E/AndroidRuntime(1010): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-23 10:40:52.550: E/AndroidRuntime(1010): at dalvik.system.NativeStart.main(Native Method)
04-23 10:40:52.550: E/AndroidRuntime(1010): Caused by: java.lang.NullPointerException
04-23 10:40:52.550: E/AndroidRuntime(1010): at com.example.instances_temperature.Tabel.onCreate(Tabel.java:26)
04-23 10:40:52.550: E/AndroidRuntime(1010): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-23 10:40:52.550: E/AndroidRuntime(1010): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-23 10:40:52.550: E/AndroidRuntime(1010): ... 11 more
line 26 would be this:
value = intentObject.getIntExtra("max", 0);
You have to use the code below
int maxValue = getIntent().getExtras().getInt("max");
inside onCreate().
Hope it will solve your problem..
You have not declared intentObject...
Use this:
value = getIntent().getIntExtra("max", 0);
use this
value = getIntent().getStringExtra("max");
instead of this
value = intentObject.getIntExtra("max", 0);
I am getting a Java null pointer exception Unable to start receiver error,
My LogCat
04-23 21:55:16.889: I/TextView(8039): *****onCrecateContextMenu::isInputMethodTarget:true, isIMEChangable;true
04-23 21:55:25.479: D/AndroidRuntime(8039): Shutting down VM
04-23 21:55:25.479: W/dalvikvm(8039): threadid=1: thread exiting with uncaught exception (group=0x40018578)
04-23 21:55:25.479: E/AndroidRuntime(8039): FATAL EXCEPTION: main
04-23 21:55:25.479: E/AndroidRuntime(8039): java.lang.RuntimeException: Unable to start receiver com.yp.iss_project.CbReceiver: java.lang.NullPointerException
04-23 21:55:25.479: E/AndroidRuntime(8039): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1809)
04-23 21:55:25.479: E/AndroidRuntime(8039): at android.app.ActivityThread.access$2400(ActivityThread.java:117)
04-23 21:55:25.479: E/AndroidRuntime(8039): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
04-23 21:55:25.479: E/AndroidRuntime(8039): at android.os.Handler.dispatchMessage(Handler.java:99)
04-23 21:55:25.479: E/AndroidRuntime(8039): at android.os.Looper.loop(Looper.java:130)
04-23 21:55:25.479: E/AndroidRuntime(8039): at android.app.ActivityThread.main(ActivityThread.java:3687)
04-23 21:55:25.479: E/AndroidRuntime(8039): at java.lang.reflect.Method.invokeNative(Native Method)
04-23 21:55:25.479: E/AndroidRuntime(8039): at java.lang.reflect.Method.invoke(Method.java:507)
04-23 21:55:25.479: E/AndroidRuntime(8039): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
04-23 21:55:25.479: E/AndroidRuntime(8039): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
04-23 21:55:25.479: E/AndroidRuntime(8039): at dalvik.system.NativeStart.main(Native Method)
04-23 21:55:25.479: E/AndroidRuntime(8039): Caused by: java.lang.NullPointerException
04-23 21:55:25.479: E/AndroidRuntime(8039): at com.yp.iss_project.CbReceiver.onReceive(CbReceiver.java:272)
04-23 21:55:25.479: E/AndroidRuntime(8039): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1798)
04-23 21:55:25.479: E/AndroidRuntime(8039): ... 10 more
04-23 21:56:57.819: W/KeyCharacterMap(8162): No keyboard for id 0
04-23 21:56:57.819: W/KeyCharacterMap(8162): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
04-23 21:57:00.359: I/TextView(8162): *****onCrecateContextMenu::isInputMethodTarget:true, isIMEChangable;true
04-23 21:57:08.069: D/AndroidRuntime(8162): Shutting down VM
04-23 21:57:08.069: W/dalvikvm(8162): threadid=1: thread exiting with uncaught exception (group=0x40018578)
04-23 21:57:08.069: E/AndroidRuntime(8162): FATAL EXCEPTION: main
04-23 21:57:08.069: E/AndroidRuntime(8162): java.lang.RuntimeException: Unable to start receiver com.yp.iss_project.CbReceiver: java.lang.NullPointerException
04-23 21:57:08.069: E/AndroidRuntime(8162): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1809)
04-23 21:57:08.069: E/AndroidRuntime(8162): at andr oid.app.ActivityThread.access$2400(ActivityThread.java:117)
04-23 21:57:08.069: E/AndroidRuntime(8162): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
04-23 21:57:08.069: E/AndroidRuntime(8162): at android.os.Handler.dispatchMessage(Handler.java:99)
04-23 21:57:08.069: E/AndroidRuntime(8162): at android.os.Looper.loop(Looper.java:130)
04-23 21:57:08.069: E/AndroidRuntime(8162): at android.app.ActivityThread.main(ActivityThread.java:3687)
04-23 21:57:08.069: E/AndroidRuntime(8162): at java.lang.reflect.Method.invokeNative(Native Method)
04-23 21:57:08.069: E/AndroidRuntime(8162): at java.lang.reflect.Method.invoke(Method.java:507)
04-23 21:57:08.069: E/AndroidRuntime(8162): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
04-23 21:57:08.069: E/AndroidRuntime(8162): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
04-23 21:57:08.069: E/AndroidRuntime(8162): at dalvik.system.NativeStart.main(Native Method)
04-23 21:57:08.069: E/AndroidRuntime(8162): Caused by: java.lang.NullPointerException
04-23 21:57:08.069: E/AndroidRuntime(8162): at com.yp.iss_project.CbReceiver.onReceive(CbReceiver.java:273)
04-23 21:57:08.069: E/AndroidRuntime(8162): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1798)
04-23 21:57:08.069: E/AndroidRuntime(8162): ... 10 more
04-23 21:59:10.639: I/TextView(8265): *****onCrecateContextMenu::isInputMethodTarget:true, isIMEChangable;true
04-23 21:59:19.979: D/AndroidRuntime(8265): Shutting down VM
04-23 21:59:19.979: W/dalvikvm(8265): threadid=1: thread exiting with uncaught exception (group=0x40018578)
My broadcast receiver is
public static String str;
public static int my;
public static String MSG = encrypt.message;
public final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public void onReceive(Context context, Intent intent) {
//---get the CB message passed in---
Bundle bundle = intent.getExtras();
SmsCbMessage[] msgs = null;
if (bundle != null) {
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsCbMessage[pdus.length];
for (int i=0; i<msgs.length; i++) {
msgs[i] = SmsCbMessage.createFromPdu((byte[])pdus[i]);
str = "";
str +="" +msgs[i].getGeographicalScope() + msgs[i].getMessageCode() + msgs[i].getMessageIdentifier() + msgs[i].getUpdateNumber();
my = msgs[i].getGeographicalScope() + msgs[i].getMessageCode() + msgs[i].getMessageIdentifier() + msgs[i].getUpdateNumber();
if(str != "")
{
Toast.makeText(context, "CB: " +str, Toast.LENGTH_LONG).show();
Toast.makeText(context, "MY: " +my, Toast.LENGTH_LONG).show();
{
String cipherText="";
for(int y=0;y<MSG.length();y++)
{
int charPosition = ALPHABET.indexOf(MSG.charAt(y));
int keyVal = (my + charPosition)%26;
char replaceVal = this.ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}
Toast.makeText(context, "CipherText: " +cipherText, Toast.LENGTH_LONG).show();
}
}
}
abortBroadcast();
}
Removed
public static String MSG = encrypt.message;
and replaced all occurrences of MSG with
encrypt.message
My mistake was with passing the value pf message from the encrypt class, as the MSG value declared in the receiver class is a null I've received a null pointer exception.
I have 2 devices. Droid x3 w/ Gingerbread and a Nexus 7 w/ Jellybean 4.2.2.
I compile and run this code on my Droid x3 and it runs perfectly.
Yet the exact same code I run on the Nexus 7 and it breaks.
Code and Stack trace included.
Thanks for the help!
package com.jacobschellenbergflickrsearch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class DataDownloader {
String apiKey = "bc370c6386192bf6e2f950cdfddfda48";
//String url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bc370c6386192bf6e2f950cdfddfda48&nojsoncallback=1&text=monkey&format=json&per_page=10";
public String buildUrl(String searchMethod, String searchQuery, int perpage){
String url = String.format("http://api.flickr.com/services/rest/?method=%s&api_key=%s&nojsoncallback=1&text=%s&format=json&per_page=%s", searchMethod, this.apiKey, searchQuery, perpage);
String result = null;
try{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while(true)
{
s = buf.readLine();
if(s==null || s.length()==0){
break;
}
sb.append(s);
}
buf.close();
ips.close();
result = sb.toString();
}
catch (IllegalStateException e) {
e.printStackTrace();
result = "IllegalStateException";
}
catch (IOException e) {
e.printStackTrace();
result = "IOException";
} catch (URISyntaxException e) {
e.printStackTrace();
result = "URISyntaxException";
}
return "Query: " + url + " : Result: " + result;
}
}
05-01 13:47:04.742: D/AndroidRuntime(4526): Shutting down VM 05-01
13:47:04.742: W/dalvikvm(4526): threadid=1: thread exiting with
uncaught exception (group=0x41377930) 05-01 13:47:04.752:
E/AndroidRuntime(4526): FATAL EXCEPTION: main 05-01 13:47:04.752:
E/AndroidRuntime(4526): java.lang.IllegalStateException: Could not
execute method of the activity 05-01 13:47:04.752:
E/AndroidRuntime(4526): at
android.view.View$1.onClick(View.java:3599) 05-01 13:47:04.752:
E/AndroidRuntime(4526): at
android.view.View.performClick(View.java:4204) 05-01 13:47:04.752:
E/AndroidRuntime(4526): at
android.view.View$PerformClick.run(View.java:17355) 05-01
13:47:04.752: E/AndroidRuntime(4526): at
android.os.Handler.handleCallback(Handler.java:725) 05-01
13:47:04.752: E/AndroidRuntime(4526): at
android.os.Handler.dispatchMessage(Handler.java:92) 05-01
13:47:04.752: E/AndroidRuntime(4526): at
android.os.Looper.loop(Looper.java:137) 05-01 13:47:04.752:
E/AndroidRuntime(4526): at
android.app.ActivityThread.main(ActivityThread.java:5041) 05-01
13:47:04.752: E/AndroidRuntime(4526): at
java.lang.reflect.Method.invokeNative(Native Method) 05-01
13:47:04.752: E/AndroidRuntime(4526): at
java.lang.reflect.Method.invoke(Method.java:511) 05-01 13:47:04.752:
E/AndroidRuntime(4526): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-01 13:47:04.752: E/AndroidRuntime(4526): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-01
13:47:04.752: E/AndroidRuntime(4526): at
dalvik.system.NativeStart.main(Native Method) 05-01 13:47:04.752:
E/AndroidRuntime(4526): Caused by:
java.lang.reflect.InvocationTargetException 05-01 13:47:04.752:
E/AndroidRuntime(4526): at
java.lang.reflect.Method.invokeNative(Native Method) 05-01
13:47:04.752: E/AndroidRuntime(4526): at
java.lang.reflect.Method.invoke(Method.java:511) 05-01 13:47:04.752:
E/AndroidRuntime(4526): at
android.view.View$1.onClick(View.java:3594) 05-01 13:47:04.752:
E/AndroidRuntime(4526): ... 11 more 05-01 13:47:04.752:
E/AndroidRuntime(4526): Caused by:
android.os.NetworkOnMainThreadException 05-01 13:47:04.752:
E/AndroidRuntime(4526): at
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
05-01 13:47:04.752: E/AndroidRuntime(4526): at
java.net.InetAddress.lookupHostByName(InetAddress.java:385) 05-01
13:47:04.752: E/AndroidRuntime(4526): at
java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 05-01
13:47:04.752: E/AndroidRuntime(4526): at
java.net.InetAddress.getAllByName(InetAddress.java:214) 05-01
13:47:04.752: E/AndroidRuntime(4526): at
org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
05-01 13:47:04.752: E/AndroidRuntime(4526): at
org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-01 13:47:04.752: E/AndroidRuntime(4526): at
org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-01 13:47:04.752: E/AndroidRuntime(4526): at
org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-01 13:47:04.752: E/AndroidRuntime(4526): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-01 13:47:04.752: E/AndroidRuntime(4526): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-01 13:47:04.752: E/AndroidRuntime(4526): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-01 13:47:04.752: E/AndroidRuntime(4526): at
com.jacobschellenbergflickrsearch.DataDownloader.buildUrl(DataDownloader.java:31)
05-01 13:47:04.752: E/AndroidRuntime(4526): at
com.jacobschellenbergflickrsearch.MainActivity.searchImage(MainActivity.java:47)
05-01 13:47:04.752: E/AndroidRuntime(4526): ... 14 more 05-01
13:47:04.802: D/dalvikvm(4526): GC_CONCURRENT freed 210K, 5% free
7474K/7812K, paused 5ms+2ms, total 46ms
Caused by: android.os.NetworkOnMainThreadException
You are doing network I/O on the main application thread. This is an exceptionally bad idea on any version of Android, and it raises an actual exception on Android 4.0+.
Please perform your network I/O on a background thread, such as by using an AsyncTask.
HttpResponse response = client.execute(request);
That is your problem. Do not call network actions on the UI thread. You should not do that ever. Since ICS it is forbidden.
Use a AsyncTask and call the client.execute() inside doInBackground(). That will fix your problem.
As the error says you are doing a newtwork call on the main thread...you cannot do that, it must be in a seperate thread
I'm trying to retrieve the data from my database through a cursor object once the database has been queried. I seem to be getting an error on my cursor.close() and when closing my database. This has been fine up until the point but I started receiving 'cursor finalizer' errors when accessing classes from different intents.
At the moment I seem to have my cursor objects closing in an incorrect manner.
As an example heres how Im trying to retrieve all the data to populate a listview within the onCreate method of my class.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appointmentview);
searchedAppView = (ListView)findViewById(android.R.id.list);
DBHandlerApp DBAppointments = new DBHandlerApp(this, null, null);
DBHandlerApp searchApps = new DBHandlerApp(this, null, null);
searchApps.open();
Cursor cursor = searchApps.getAppointmentsData();
startManagingCursor(cursor);
#SuppressWarnings("static-access")
String [] from = new String [] {DBAppointments.KEY_NAMEAPP, DBAppointments.KEY_TYPEAPP, DBAppointments.KEY_TIMEAPP, DBAppointments.KEY_DATEAPP, DBAppointments.KEY_COMMENTAPP};
int [] to = new int [] {R.id.txtAppointName, R.id.txtAppointType, R.id.txtAppointTime, R.id.txtAppointDate, R.id.txtAppointCom};
#SuppressWarnings("deprecation")
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.setappointviews, cursor, from, to);
searchedAppView.setAdapter(cursorAdapter);
searchAppoints = (ImageButton) findViewById(R.id.btnSearchAppointName);
searchAppName = (EditText) findViewById(R.id.inputAppointName);
searchAppoints.setOnClickListener(this);
}
Heres the method 'getAppointmentData' of the DBHandlerApp class:
public Cursor getAppointmentsData() {
String [] columns = new String[]{KEY_ROWAPPID, KEY_NAMEAPP, KEY_TYPEAPP, KEY_TIMEAPP, KEY_DATEAPP, KEY_COMMENTAPP};
Cursor c = ourDatabase.query(DATABASE_TABLEAPP, columns, null, null, null, null, KEY_NAMEAPP + " ASC", null);
//*****Closing the cursor object.*****
c.close();
return c;
Logcat error:
01-31 17:44:34.220: E/AndroidRuntime(269): FATAL EXCEPTION: main
01-31 17:44:34.220: E/AndroidRuntime(269): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.flybase2/com.example.flybase2.ViewAppointments}: java.lang.IllegalStateException: attempt to re-open an already-closed object: android.database.sqlite.SQLiteQuery (mSql = SELECT _id, app_name, app_type, app_time, app_date, app_comments FROM appointmentsTable ORDER BY app_name ASC)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.os.Looper.loop(Looper.java:123)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-31 17:44:34.220: E/AndroidRuntime(269): at java.lang.reflect.Method.invokeNative(Native Method)
01-31 17:44:34.220: E/AndroidRuntime(269): at java.lang.reflect.Method.invoke(Method.java:521)
01-31 17:44:34.220: E/AndroidRuntime(269): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-31 17:44:34.220: E/AndroidRuntime(269): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-31 17:44:34.220: E/AndroidRuntime(269): at dalvik.system.NativeStart.main(Native Method)
01-31 17:44:34.220: E/AndroidRuntime(269): Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: android.database.sqlite.SQLiteQuery (mSql = SELECT _id, app_name, app_type, app_time, app_date, app_comments FROM appointmentsTable ORDER BY app_name ASC)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:34)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:64)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:283)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:264)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.support.v4.widget.CursorAdapter.getCount(CursorAdapter.java:202)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.widget.ListView.setAdapter(ListView.java:436)
01-31 17:44:34.220: E/AndroidRuntime(269): at com.example.flybase2.ViewAppointments.onCreate(ViewAppointments.java:54)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-31 17:44:34.220: E/AndroidRuntime(269): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-31 17:44:34.220: E/AndroidRuntime(269): ... 11 more
Currently at the moment I do not close the database using .searchApps.close();. If do this then I get the following logcat error:
01-31 17:52:17.324: E/AndroidRuntime(277): FATAL EXCEPTION: main
01-31 17:52:17.324: E/AndroidRuntime(277): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.flybase2/com.example.flybase2.ViewAppointments}: java.lang.IllegalStateException: attempt to re-open an already-closed object: android.database.sqlite.SQLiteQuery (mSql = SELECT _id, app_name, app_type, app_time, app_date, app_comments FROM appointmentsTable ORDER BY app_name ASC)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.os.Looper.loop(Looper.java:123)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-31 17:52:17.324: E/AndroidRuntime(277): at java.lang.reflect.Method.invokeNative(Native Method)
01-31 17:52:17.324: E/AndroidRuntime(277): at java.lang.reflect.Method.invoke(Method.java:521)
01-31 17:52:17.324: E/AndroidRuntime(277): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-31 17:52:17.324: E/AndroidRuntime(277): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-31 17:52:17.324: E/AndroidRuntime(277): at dalvik.system.NativeStart.main(Native Method)
01-31 17:52:17.324: E/AndroidRuntime(277): Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: android.database.sqlite.SQLiteQuery (mSql = SELECT _id, app_name, app_type, app_time, app_date, app_comments FROM appointmentsTable ORDER BY app_name ASC)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:34)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:64)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:283)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:264)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.support.v4.widget.CursorAdapter.getCount(CursorAdapter.java:202)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.widget.ListView.setAdapter(ListView.java:436)
01-31 17:52:17.324: E/AndroidRuntime(277): at com.example.flybase2.ViewAppointments.onCreate(ViewAppointments.java:56)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-31 17:52:17.324: E/AndroidRuntime(277): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-31 17:52:17.324: E/AndroidRuntime(277): ... 11 more
You're closing your cursor in the wrong place. You should close a cursor when you're completely done using it, you're closing it right after populating it, before returning it from your getAppointmentData method.
Simply removing the close call from that method should fix your problem because when you use startManagingCursor, the activity handles closing it.
As an aside, startManagingCursor is depreciated in favor of using Loaders.
I do not exactly know what the problem is. However, the method startManagingCursor(...) is deprecated and should not be used, see: http://developer.android.com/reference/android/app/Activity.html#startManagingCursor(android.database.Cursor)
A better way is to use a CursorLoader.
I'm build a app that consist of user login and registration but every time I test it on the emulator I receive a force close. Below are the errors I'm receiving in the log cat:
08-14 14:06:28.853: D/dalvikvm(828): GC_FOR_ALLOC freed 108K, 3% free 8262K/8455K, paused 89ms, total 92ms
08-14 14:06:29.273: I/Choreographer(828): Skipped 72 frames! The application may be doing too much work on its main thread.
08-14 14:06:29.373: D/gralloc_goldfish(828): Emulator without GPU emulation detected.
08-14 14:06:29.373: D/dalvikvm(828): GC_CONCURRENT freed 5K, 3% free 8660K/8839K, paused 110ms+28ms, total 365ms
08-14 14:06:29.902: I/Choreographer(828): Skipped 85 frames! The application may be doing too much work on its main thread.
08-14 14:06:32.533: D/dalvikvm(828): GC_CONCURRENT freed 32K, 3% free 9027K/9223K, paused 81ms+111ms, total 343ms
08-14 14:06:32.813: I/Choreographer(828): Skipped 71 frames! The application may be doing too much work on its main thread.
08-14 14:06:33.303: I/Choreographer(828): Skipped 38 frames! The application may be doing too much work on its main thread.
08-14 14:06:39.854: D/InputEventConsistencyVerifier(828): KeyEvent: ACTION_UP but key was not down.
08-14 14:06:39.854: D/InputEventConsistencyVerifier(828): in android.widget.EditText#412b2f68
08-14 14:06:39.854: D/InputEventConsistencyVerifier(828): 0: sent at 1614282000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_M, scanCode=50, metaState=0, flags=0x8, repeatCount=0, eventTime=1614282, downTime=1614282, deviceId=0, source=0x301 }
08-14 14:06:39.874: D/InputEventConsistencyVerifier(828): KeyEvent: ACTION_UP but key was not down.
08-14 14:06:39.874: D/InputEventConsistencyVerifier(828): in android.widget.EditText#412b2f68
08-14 14:06:39.874: D/InputEventConsistencyVerifier(828): 0: sent at 1614392000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=1614392, downTime=1614282, deviceId=0, source=0x301 }
08-14 14:06:39.874: D/InputEventConsistencyVerifier(828): -- recent events --
08-14 14:06:39.874: D/InputEventConsistencyVerifier(828): 1: sent at 1614282000000, (unhandled) KeyEvent { action=ACTION_UP, keyCode=KEYCODE_M, scanCode=50, metaState=0, flags=0x80000008, repeatCount=0, eventTime=1614282, downTime=1614282, deviceId=0, source=0x301 }
08-14 14:07:02.362: D/AndroidRuntime(828): Shutting down VM
08-14 14:07:02.362: W/dalvikvm(828): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
**08-14 14:07:02.472: E/AndroidRuntime(828): FATAL EXCEPTION: main
08-14 14:07:02.472: E/AndroidRuntime(828): android.os.NetworkOnMainThreadException
08-14 14:07:02.472: E/AndroidRuntime(828): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-14 14:07:02.472: E/AndroidRuntime(828): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
08-14 14:07:02.472: E/AndroidRuntime(828): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
08-14 14:07:02.472: E/AndroidRuntime(828): at libcore.io.IoBridge.connect(IoBridge.java:112)
08-14 14:07:02.472: E/AndroidRuntime(828): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-14 14:07:02.472: E/AndroidRuntime(828): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-14 14:07:02.472: E/AndroidRuntime(828): at java.net.Socket.connect(Socket.java:842)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-14 14:07:02.472: E/AndroidRuntime(828): at library.JSONParser.getJSONFromUrl(JSONParser.java:41)
08-14 14:07:02.472: E/AndroidRuntime(828): at library.UserFunctions.loginUser(UserFunctions.java:40)
08-14 14:07:02.472: E/AndroidRuntime(828): at com.thryfting.www.LoginActivity.onClick(LoginActivity.java:66)
08-14 14:07:02.472: E/AndroidRuntime(828): at android.view.View.performClick(View.java:4084)
08-14 14:07:02.472: E/AndroidRuntime(828): at android.view.View$PerformClick.run(View.java:16966)
08-14 14:07:02.472: E/AndroidRuntime(828): at android.os.Handler.handleCallback(Handler.java:615)
08-14 14:07:02.472: E/AndroidRuntime(828): at android.os.Handler.dispatchMessage(Handler.java:92)
08-14 14:07:02.472: E/AndroidRuntime(828): at android.os.Looper.loop(Looper.java:137)
08-14 14:07:02.472: E/AndroidRuntime(828): at android.app.ActivityThread.main(ActivityThread.java:4745)
08-14 14:07:02.472: E/AndroidRuntime(828): at java.lang.reflect.Method.invokeNative(Native Method)
08-14 14:07:02.472: E/AndroidRuntime(828): at java.lang.reflect.Method.invoke(Method.java:511)
08-14 14:07:02.472: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-14 14:07:02.472: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-14 14:07:02.472: E/AndroidRuntime(828): at dalvik.system.NativeStart.main(Native Method)**
Updated code for register activity:
package com.thryfting.www;
import org.json.JSONException;
import org.json.JSONObject;
import library.DatabaseHandler;
import library.UserFunctions;
import android.content.Intent;
import android.os.AsyncTask;
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;
import com.actionbarsherlock.app.SherlockActivity;
public class RegisterActivity extends SherlockActivity implements OnClickListener{
Button btnRegister;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
TextView loginScreen;
//JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
loginScreen = (TextView) findViewById(R.id.link_to_login);
inputEmail = (EditText) findViewById(R.id.etemailSignup);
inputPassword = (EditText) findViewById(R.id.etPasswordSignup);
inputFullName = (EditText) findViewById(R.id.etFullnameSignup);
btnRegister = (Button) findViewById(R.id.btnRegister);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
loginScreen.setOnClickListener(this);
btnRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btnRegister:
new register().execute(KEY_SUCCESS);
break;
case R.id.link_to_login:
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
//Close Registration View
finish();
break;
}
}
public class register extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
try{
if(json.getString(KEY_SUCCESS) != null){
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
//user successfully registered
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
//Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
}else{
//Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch(JSONException e){
e.printStackTrace();
} finally{
//Launch Dashboard
Intent dashboard = new Intent (getApplicationContext(), Timeline.class);
//Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Close registration screen
finish();
}
return null;
}
}
}
New error messages below:
08-15 14:53:32.940: W/dalvikvm(865): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
08-15 14:53:33.060: E/AndroidRuntime(865): FATAL EXCEPTION: AsyncTask #1
08-15 14:53:33.060: E/AndroidRuntime(865): java.lang.RuntimeException: An error occured while executing doInBackground()
08-15 14:53:33.060: E/AndroidRuntime(865): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-15 14:53:33.060: E/AndroidRuntime(865): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.lang.Thread.run(Thread.java:856)
08-15 14:53:33.060: E/AndroidRuntime(865): Caused by: java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=register
08-15 14:53:33.060: E/AndroidRuntime(865): at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
08-15 14:53:33.060: E/AndroidRuntime(865): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
08-15 14:53:33.060: E/AndroidRuntime(865): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-15 14:53:33.060: E/AndroidRuntime(865): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-15 14:53:33.060: E/AndroidRuntime(865): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-15 14:53:33.060: E/AndroidRuntime(865): at library.JSONParser.getJSONFromUrl(JSONParser.java:41)
08-15 14:53:33.060: E/AndroidRuntime(865): at library.UserFunctions.registerUser(UserFunctions.java:63)
08-15 14:53:33.060: E/AndroidRuntime(865): at com.thryfting.www.RegisterActivity$register.doInBackground(RegisterActivity.java:89)
08-15 14:53:33.060: E/AndroidRuntime(865): at com.thryfting.www.RegisterActivity$register.doInBackground(RegisterActivity.java:1)
08-15 14:53:33.060: E/AndroidRuntime(865): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-15 14:53:33.060: E/AndroidRuntime(865): ... 5 more
08-15 14:53:34.812: I/Choreographer(865): Skipped 93 frames! The application may be doing too much work on its main thread.
08-15 14:53:36.512: I/Process(865): Sending signal. PID: 865 SIG: 9
public JSONObject registerUser(String name, String email, String password){
//building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
//Getting JSON object
JSONObject json = jsonParser.getJSONFromUrl(register_tag, params);
//return json
return json;
}
Your getting a StrictMode violation. This means that you are doing something blocking on the UI Thread. Hence the reason for
android.os.NetworkOnMainThreadException
From the rest of your LOG it appears your performing a web request.
Make sure that HTTP request is wrapped in an AsyncTask (or something similar)
It seems like you are trying to do your login and registration on the main Thread. First of all this is bad practice, and it can't be done on recent API levels.
All you need to do is make your network connections in a separate thread, be it an AsyncTask or just a plain old Thread()
as an example :
use this
public void login()
{
new Thread(new Runnable() {
#Override
public void run() {
//your network connection goes here
}
}).start();
}
instead of :
public void login()
{
//your network connection goes here
}
Try to check the same in a mobile with internet connectivity.
The logcat also displays that the emulator doesnt has a GPS connectivity.