When I attempt to connect to a local Database on my computer I get a list of problems.
07-31 21:29:53.036: I/System.out(1470): 1
07-31 21:29:53.046: I/System.out(1470): 2
07-31 21:29:53.106: I/System.out(1470): 3
07-31 21:29:53.326: W/EGL_emulation(1470): eglSurfaceAttrib not implemented
07-31 21:30:00.126: E/JSON(1470):{"tag":"register","success":0,"error":1,"error_msg":"Error occured in Registartion"}n
07-31 21:30:00.126: I/System.out(1470): 4
07-31 21:30:00.156: I/System.out(1470): 5
07-31 21:30:00.156: I/System.out(1470): ERROR
07-31 21:30:00.186: W/System.err(1470): java.lang.NullPointerException
07-31 21:30:00.186: W/System.err(1470): at com.example.skelotong.RegularUsercreation$ruc.doInBackground(RegularUsercreation.java:138)
07-31 21:30:00.196: W/System.err(1470): at com.example.skelotong.RegularUsercreation$ruc.doInBackground(RegularUsercreation.java:1)
07-31 21:30:00.196: W/System.err(1470): at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-31 21:30:00.196: W/System.err(1470): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-31 21:30:00.196: W/System.err(1470): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-31 21:30:00.206: W/System.err(1470): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-31 21:30:00.206: W/System.err(1470): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-31 21:30:00.206: W/System.err(1470): at java.lang.Thread.run(Thread.java:841)
07-31 21:30:00.206: I/System.out(1470): 9
07-31 21:30:00.326: D/AndroidRuntime(1470): Shutting down VM
07-31 21:30:00.326: W/dalvikvm(1470): threadid=1: thread exiting with uncaught exception (group=0xb1a32ba8)
07-31 21:30:00.336: E/AndroidRuntime(1470): FATAL EXCEPTION: main
07-31 21:30:00.336: E/AndroidRuntime(1470): Process: com.example.skelotong, PID: 1470
07-31 21:30:00.336: E/AndroidRuntime(1470): java.lang.NullPointerException
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.example.skelotong.RegularUsercreation$ruc.onPostExecute(RegularUsercreation.java:184)
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.example.skelotong.RegularUsercreation$ruc.onPostExecute(RegularUsercreation.java:1)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.AsyncTask.finish(AsyncTask.java:632)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.Handler.dispatchMessage(Handler.java:102)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.Looper.loop(Looper.java:136)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-31 21:30:00.336: E/AndroidRuntime(1470): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 21:30:00.336: E/AndroidRuntime(1470): at java.lang.reflect.Method.invoke(Method.java:515)
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-31 21:30:00.336: E/AndroidRuntime(1470): at dalvik.system.NativeStart.main(Native Method)
07-31 21:30:03.356: I/Process(1470): Sending signal. PID: 1470 SIG: 9
07-31 21:30:05.946: D/dalvikvm(1499): GC_FOR_ALLOC freed 179K, 12% free 3467K/3932K, paused 141ms, total 144ms
07-31 21:30:06.636: D/(1499): HostConnection::get() New Host Connection established 0xb8f39498, tid 1499
07-31 21:30:06.786: W/EGL_emulation(1499): eglSurfaceAttrib not implemented
07-31 21:30:06.796: D/OpenGLRenderer(1499): Enabling debug mode 0
Here is the code that I attempt to run.
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegularUsercreation extends ActionBarActivity implements Runnable {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
EditText inputUsername;
EditText dateofbirth;
EditText zip;
// EditText skils;
// 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";
private Handler mHandler = new Handler(Looper.getMainLooper());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regular_usercreation);
}
public void clicker(View view) {
new ruc().execute((String[]) null);
}
public void ss(View view) {
Intent i = new Intent(getApplicationContext(), RegisterClass.class);
startActivity(i);
// Close Registration View
finish();
}
private class ruc extends AsyncTask<String, Integer, Boolean> {
final ProgressDialog pd = new ProgressDialog(RegularUsercreation.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.setMessage("Please wait");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCanceledOnTouchOutside(false);
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
System.out.println("1");
}
#Override
protected Boolean doInBackground(String... params) {
System.out.println(2);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.FullName2);
inputEmail = (EditText) findViewById(R.id.Email2);
inputPassword = (EditText) findViewById(R.id.Password2);
inputUsername = (EditText) findViewById(R.id.Username2);
dateofbirth = (EditText) findViewById(R.id.DOB2);
zip = (EditText) findViewById(R.id.ZipCode2);
btnRegister = (Button) findViewById(R.id.create2);
btnLinkToLogin = (Button) findViewById(R.id.cancel2);
registerErrorMsg = (TextView) findViewById(R.id.errormessage3);
// skils = (EditText) findViewById(R.id.skills1);
System.out.println("3");
// Register Button Click event
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String usernmae = inputUsername.getText().toString();
String birth = dateofbirth.getText().toString();
String zipcode = zip.getText().toString();
// String skills = skils.getText().toString();
UserFunction userFunction = new UserFunction();
JSONObject json = userFunction.registerUser(name, email, password,
usernmae, birth, zipcode);
System.out.println(4);
// check for login response
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
System.out.println("5");
if (Integer.parseInt(res) == 1) {
publishProgress(1);
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
System.out.println(6);
// 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));
System.out.println("7");
return true;
} else {
System.out.println("ERROR");
// Error in registration
//registerErrorMsg
// .setText("Error occured in registration");
return false;
}
}
} catch (JSONException e) {
publishProgress(1);
e.printStackTrace();
System.out.println("9");
return false;
}
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
if (values.equals(1)) {
pd.setMessage("Almost Done");
}
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == true) {
// launch dashboard
Intent dashboard = new Intent(getApplicationContext(),
HomePage.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}
if (result == false) {
registerErrorMsg.setText("Error occured in registration");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.regular_usercreation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void run() {
// TODO Auto-generated method stub
mHandler.post(new Runnable() {
public void run() {
new ruc();
ruc.execute(RegularUsercreation.this);
}
});
}
}
How can this problem be fixed and what can be done in the future to prevent this?
Also why does this happen.
from the looks of is either res is null or something's null within these lines
if (Integer.parseInt(res) == 1) {
publishProgress(1);
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
However its hard to be sure. publishProgress or getApplicationContext may have something throwing the NullPointerException as well. Try this for debugging the problem : since you're using eclipse, you can use debugger instead of println, its way more powerful. A useful tutorial. If you don't want to use the debugger, print the values instead of numbers. They'll provide much more useeful context.
Related
I switched from running my app on a phone to a nexus 10 tablet and now it says "unfortunately the application has stopped."
The tablet is running 4.4.2, my target api is set to 19 in the manifest.
When I run it in debug mode I get Source Not Found. I tried clicking edit source lookup path and adding my project and had no luck.
I've looked all over the internet and haven't had any luck solving this problem. Any suggestions would be a big help.
"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.looper.video/com.looper.video.MainActivity}: java.lang.NullPointerException"
Edit:
MainActivity:
package com.looper.video;
public class MainActivity extends Activity {
private VideoView video;
private MediaController ctlr;
final Uri firstVideoPath = Uri.parse("android.resource://com.looper.video/" + R.raw.wildlife);
final Uri secondVideoPath = Uri.parse("android.resource://com.looper.video/" + R.raw.wildlife1);
private String videosPath = Environment.getExternalStorageDirectory() + "/videos/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File folder = new File(videosPath);
File[] customFiles = folder.listFiles();
List<String> customFileNames = new ArrayList<String>();
for(File file : customFiles) {
customFileNames.add(file.getName());
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, customFileNames);
spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles);
spinner.setAdapter(spinnerArrayAdapter);
video = (VideoView)findViewById(R.id.videoView1);
ctlr = new MediaController(this);
final Button firstVideoBtn = (Button) findViewById(R.id.firstVideoBtn);
firstVideoBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
playFirstVideo();
}
});
final Button secondVideoBtn = (Button) findViewById(R.id.secondVideoBtn);
secondVideoBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
playSecondVideo();
}
});
}
public void playFeatured(View v) {
try {
Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles);
String strPath = videosPath + spinner.getSelectedItem().toString();
Toast.makeText(this, strPath, Toast.LENGTH_LONG).show();
//Uri path = Uri.parse(videosPath + spinner.getSelectedItem().toString());
video.setVideoPath(strPath);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
playSecondVideo();
}
});
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
public void playFirstVideo() {
video.setVideoURI(firstVideoPath);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
playSecondVideo();
}
});
}
public void playSecondVideo() {
SharedPreferences sp = getSharedPreferences("schedule", Context.MODE_PRIVATE);
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String startTime = sp.getString("startTime", "");
String endTime = sp.getString("endTime", "");
/*
//SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
//Date dateStartTime = parser.parse(startTime);
//Date dateEndTime = parser.parse(endTime);
Date now = new Date();
try {
if (userDate.after(ten) && userDate.before(eighteen)) {
}
} catch (ParseException e) {
// Invalid date was entered
}
System.out.println("Now:"+now);
System.out.println("Start"+startTime);
System.out.println("End:"+endTime);
//if(now.before(dateEndTime) && now.after(dateStartTime)){
//disableAll();
//} else {
*
*/
video.setVideoURI(secondVideoPath);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
playSecondVideo();
}
});
//}
}
public void admin(View view)
{
//MySQLiteHelper db = new MySQLiteHelper(this);
//final String password = db.getUser(7).getPassword();
//db.close();
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText pass = new EditText(this);
alert.setView(pass);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = pass.getText().toString().trim();
SharedPreferences sp1 = getSharedPreferences("Login", 0);
//String username = sp1.getString("UserName", "");
String password = sp1.getString("Password", "");
if(value.equals(password)) {
Intent intent = new Intent(getBaseContext(),Admin.class);
startActivity(intent);
}
//Toast.makeText(getApplicationContext(), password + " " + value, Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void disableAll(){
Button firstVideoBtn = (Button)findViewById(R.id.firstVideoBtn);
firstVideoBtn.setEnabled(false);
Button secondVideoBtn = (Button)findViewById(R.id.secondVideoBtn);
secondVideoBtn.setEnabled(false);
Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles);
spinner.setEnabled(false);
Button btnPlay = (Button)findViewById(R.id.btnPlayFeatured);
btnPlay.setEnabled(false);
VideoView videoView = (VideoView)findViewById(R.id.videoView1);
videoView.setEnabled(false);
}
}
Full logcat:
D/dalvikvm(2817): GC_FOR_ALLOC freed 58K, 4% free 3441K/3568K, paused 20ms, total 20ms
10-08 15:23:17.965: D/dalvikvm(2817): GC_FOR_ALLOC freed 2K, 4% free 3505K/3632K, paused 7ms, total 7ms
10-08 15:23:17.975: I/dalvikvm-heap(2817): Grow heap (frag case) to 8.739MB for 5515216-byte allocation
10-08 15:23:17.985: D/dalvikvm(2817): GC_FOR_ALLOC freed <1K, 2% free 8891K/9020K, paused 7ms, total 7ms
10-08 15:23:18.055: D/AndroidRuntime(2817): Shutting down VM
10-08 15:23:18.055: W/dalvikvm(2817): threadid=1: thread exiting with uncaught exception (group=0x4155eba8)
10-08 15:23:18.055: E/AndroidRuntime(2817): FATAL EXCEPTION: main
10-08 15:23:18.055: E/AndroidRuntime(2817): Process: com.looper.video, PID: 2817
10-08 15:23:18.055: E/AndroidRuntime(2817): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.looper.video/com.looper.video.MainActivity}: java.lang.NullPointerException
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.access$800(ActivityThread.java:135)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.os.Handler.dispatchMessage(Handler.java:102)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.os.Looper.loop(Looper.java:136)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-08 15:23:18.055: E/AndroidRuntime(2817): at java.lang.reflect.Method.invokeNative(Native Method)
10-08 15:23:18.055: E/AndroidRuntime(2817): at java.lang.reflect.Method.invoke(Method.java:515)
10-08 15:23:18.055: E/AndroidRuntime(2817): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-08 15:23:18.055: E/AndroidRuntime(2817): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-08 15:23:18.055: E/AndroidRuntime(2817): at dalvik.system.NativeStart.main(Native Method)
10-08 15:23:18.055: E/AndroidRuntime(2817): Caused by: java.lang.NullPointerException
10-08 15:23:18.055: E/AndroidRuntime(2817): at com.looper.video.MainActivity.onCreate(MainActivity.java:52)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.Activity.performCreate(Activity.java:5231)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
10-08 15:23:18.055: E/AndroidRuntime(2817): ... 11 more
This question already has answers here:
NetworkOnMainThreadException [duplicate]
(5 answers)
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
I am trying to make a simple login screen, which is being loaded correctly is user isn't already logged in.
However - pressing "LOGIN" button, crashes the app.
LoginActivity.java
package com.atsdata.flldk;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.atsdata.flldk.library.DatabaseHandler;
import com.atsdata.flldk.library.UserFunctions;
public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// 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
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// 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));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), MainActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
UserFunctions.java
package com.atsdata.flldk.library;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.content.Context;
public class UserFunctions {
private JSONParser jsonParser;
// Testing in localhost using wamp or xampp
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://<url-removed>";
private static String registerURL = "http://<url-removed>";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param email
* #param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* #param name
* #param email
* #param password
* */
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(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
log cat
03-07 06:58:40.212: D/AndroidRuntime(1440): Shutting down VM
03-07 06:58:40.212: W/dalvikvm(1440): threadid=1: thread exiting with uncaught exception (group=0xb1aa3b90)
03-07 06:58:40.222: E/AndroidRuntime(1440): FATAL EXCEPTION: main
03-07 06:58:40.222: E/AndroidRuntime(1440): Process: com.atsdata.flldk, PID: 1440
03-07 06:58:40.222: E/AndroidRuntime(1440): android.os.NetworkOnMainThreadException
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
03-07 06:58:40.222: E/AndroidRuntime(1440): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
03-07 06:58:40.222: E/AndroidRuntime(1440): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
03-07 06:58:40.222: E/AndroidRuntime(1440): at java.net.InetAddress.getAllByName(InetAddress.java:214)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-07 06:58:40.222: E/AndroidRuntime(1440): at com.atsdata.flldk.library.JSONParser.getJSONFromUrl(JSONParser.java:43)
03-07 06:58:40.222: E/AndroidRuntime(1440): at com.atsdata.flldk.library.UserFunctions.loginUser(UserFunctions.java:40)
03-07 06:58:40.222: E/AndroidRuntime(1440): at com.atsdata.flldk.LoginActivity$1.onClick(LoginActivity.java:54)
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.view.View.performClick(View.java:4424)
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.view.View$PerformClick.run(View.java:18383)
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.os.Handler.handleCallback(Handler.java:733)
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.os.Handler.dispatchMessage(Handler.java:95)
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.os.Looper.loop(Looper.java:137)
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.app.ActivityThread.main(ActivityThread.java:4998)
03-07 06:58:40.222: E/AndroidRuntime(1440): at java.lang.reflect.Method.invokeNative(Native Method)
03-07 06:58:40.222: E/AndroidRuntime(1440): at java.lang.reflect.Method.invoke(Method.java:515)
03-07 06:58:40.222: E/AndroidRuntime(1440): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-07 06:58:40.222: E/AndroidRuntime(1440): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-07 06:58:40.222: E/AndroidRuntime(1440): at dalvik.system.NativeStart.main(Native Method)
If anyone can point me in the right direction it would be great. Thanks.
You are not allowed to do network communication on the UI main thread. This is to stop your code blocking the UI and it locking up. You need to do the network work on another thread. You should read about AsyncTasks:
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html#concurrency_asynchtask
http://developer.android.com/reference/android/os/AsyncTask.html
NetworkOnMainThreadException
This means that you cannot perform network operation in the main thread (like onClick or other methods not used in another thread).
Try to put the code in
public void onClick(View view) {...}
to an AsyncTask
AsyncTask
When I click login it just attemping to login and forced closed my apps
This is my logcat:
12-13 00:19:08.809: E/JSON Parser(20761): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
12-13 00:19:08.809: W/dalvikvm(20761): threadid=9: thread exiting with uncaught exception (group=0x40018578)
12-13 00:19:08.829: E/AndroidRuntime(20761): FATAL EXCEPTION: AsyncTask #1
12-13 00:19:08.829: E/AndroidRuntime(20761): java.lang.RuntimeException: An error occured while executing doInBackground()
12-13 00:19:08.829: E/AndroidRuntime(20761): at android.os.AsyncTask$3.done(AsyncTask.java:200)
12-13 00:19:08.829: E/AndroidRuntime(20761): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
12-13 00:19:08.829: E/AndroidRuntime(20761): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
12-13 00:19:08.829: E/AndroidRuntime(20761): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
12-13 00:19:08.829: E/AndroidRuntime(20761): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
12-13 00:19:08.829: E/AndroidRuntime(20761): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
12-13 00:19:08.829: E/AndroidRuntime(20761): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
12-13 00:19:08.829: E/AndroidRuntime(20761): at java.lang.Thread.run(Thread.java:1019)
12-13 00:19:08.829: E/AndroidRuntime(20761): Caused by: java.lang.NullPointerException
12-13 00:19:08.829: E/AndroidRuntime(20761): at com.pmss.Login$AttemptLogin.doInBackground(Login.java:148)
12-13 00:19:08.829: E/AndroidRuntime(20761): at com.pmss.Login$AttemptLogin.doInBackground(Login.java:1)
12-13 00:19:08.829: E/AndroidRuntime(20761): at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-13 00:19:08.829: E/AndroidRuntime(20761): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
12-13 00:19:08.829: E/AndroidRuntime(20761): ... 4 more
12-13 00:19:15.119: E/WindowManager(20761): Activity com.pmss.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4059cf98 that was originally added here
12-13 00:19:15.119: E/WindowManager(20761): android.view.WindowLeaked: Activity com.pmss.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4059cf98 that was originally added here
12-13 00:19:15.119: E/WindowManager(20761): at android.view.ViewRoot.<init>(ViewRoot.java:263)
12-13 00:19:15.119: E/WindowManager(20761): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
12-13 00:19:15.119: E/WindowManager(20761): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
12-13 00:19:15.119: E/WindowManager(20761): at android.view.Window$LocalWindowManager.addView(Window.java:424)
12-13 00:19:15.119: E/WindowManager(20761): at android.app.Dialog.show(Dialog.java:241)
12-13 00:19:15.119: E/WindowManager(20761): at com.pmss.Login$AttemptLogin.onPreExecute(Login.java:130)
12-13 00:19:15.119: E/WindowManager(20761): at android.os.AsyncTask.execute(AsyncTask.java:391)
12-13 00:19:15.119: E/WindowManager(20761): at com.pmss.Login$1.onClick(Login.java:66)
12-13 00:19:15.119: E/WindowManager(20761): at android.view.View.performClick(View.java:2485)
12-13 00:19:15.119: E/WindowManager(20761): at android.view.View$PerformClick.run(View.java:9080)
12-13 00:19:15.119: E/WindowManager(20761): at android.os.Handler.handleCallback(Handler.java:587)
12-13 00:19:15.119: E/WindowManager(20761): at android.os.Handler.dispatchMessage(Handler.java:92)
12-13 00:19:15.119: E/WindowManager(20761): at android.os.Looper.loop(Looper.java:130)
12-13 00:19:15.119: E/WindowManager(20761): at android.app.ActivityThread.main(ActivityThread.java:3687)
12-13 00:19:15.119: E/WindowManager(20761): at java.lang.reflect.Method.invokeNative(Native Method)
12-13 00:19:15.119: E/WindowManager(20761): at java.lang.reflect.Method.invoke(Method.java:507)
12-13 00:19:15.119: E/WindowManager(20761): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
12-13 00:19:15.119: E/WindowManager(20761): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
12-13 00:19:15.119: E/WindowManager(20761): at dalvik.system.NativeStart.main(Native Method)
Line 130: pDialog.show();
Line 148: Log.d("Login attempt", json.toString());
This is my Login.java
public class Login extends ActionBarActivity implements OnClickListener {
private Button login, register;
private EditText email, password;
private JSONArray mComments = null;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://XXX.XXX.X.XX:1234/PMSS/login.php";
// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_POSITION = "position";
private static final String TAG_POSTS = "posts";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.registerlauncher);
email = (EditText) findViewById(R.id.userid);
password = (EditText) findViewById(R.id.password);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String Username = email.getText().toString();
String Password = password.getText().toString();
new AttemptLogin(Username, Password).execute();
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Login.this, Register.class);
startActivity(intent);
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// For the main activity, make sure the app icon in the action bar
// does not behave as a button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
/*
* case R.id.login: new AttemptLogin().execute(); break; case
* R.id.register: Intent i = new Intent(Login.this, Register.class);
* startActivity(i); break;
*/
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, Integer> {
private final String TAG = null;
boolean failure = false;
String res;
String Username;
String Password;
String Position;
int success;
public AttemptLogin(String Username, String Password) {
this.Username = Username;
this.Password = Password;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected Integer doInBackground(String... args) {
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", Username));
params.add(new BasicNameValuePair("password", Password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
System.out.print("Here");
// check your log for json response
Log.d("Login attempt", json.toString());
mComments = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object
// returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
// String content = c.getString(TAG_USERID);
Position = c.getString(TAG_POSITION);
}
// json success tag
success = json.getInt(TAG_SUCCESS);
res = json.getString(TAG_MESSAGE);
} catch (JSONException e) {
Log.e(TAG, "JSON error", e);
success = Integer.valueOf(0);
}
return success;
}
protected void onPostExecute(Integer success) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (success != null && success == 1) {
Log.d("Login Successful!", "res: " + res);
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", Username);
edit.commit();
if(Position == "user"){
Intent user = new Intent(Login.this, MainMenu.class);
startActivity(user);
}
else if(Position == "staff"){
Intent staff = new Intent(Login.this, StaffMainMenu.class);
startActivity(staff);
}
Toast.makeText(
Login.this,
res == null ? "Please enter both user id and password"
: res, Toast.LENGTH_LONG).show();
email.setText(null);
password.setText(null);
} else {
Log.d("Login Failure!", "res: " + res);
Toast.makeText(
Login.this,
res == null ? "Please enter both user id and password"
: res, Toast.LENGTH_LONG).show();
}
}
}
}
This is my Login.php
<?php
require("config.inc.php");
if (!empty($_POST)) {
if(empty($_POST['username']) || empty($_POST['password'])) {
$response["success"] = 0;
$response["message"] = "Please fill in the login details!";
die(json_encode($response));
}
$query = "
SELECT
email,
password,
position
FROM user
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['username'],
':position' => $_POST[],
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
$login_ok = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login Successful!";
foreach ($rows as $row) {
$post = array();
$post["position"] = $row["position"];
array_push($response["posts"], $post);
}
echo json_encode($response);
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
}
?>
What am I trying to do is that I used email and password as my login id and login password, once my login.php check database for the existing user and matching the input password is same with the password that saved in database. Once it matched, it will acquire the position value from database to Login.java to determine which interface it will go like User Main Menu and Staff Main Menu.
This is my database structure
CREATE TABLE user (
userid INT( 30 ) NOT NULL AUTO_INCREMENT ,
name VARCHAR( 100 ) NOT NULL ,
email VARCHAR( 50 ) NOT NULL ,
password VARCHAR( 20 ) NOT NULL ,
mobilenumber VARCHAR( 30 ) NOT NULL ,
address VARCHAR( 100 ) NOT NULL ,
city VARCHAR( 30 ) NOT NULL ,
postcode VARCHAR( 10 ) NOT NULL ,
state VARCHAR( 30 ) NOT NULL ,
position VARCHAR( 30 ) NULL ,
cardbalance VARCHAR( 10 ) NULL ,
PRIMARY KEY ( `userid` ) ,
UNIQUE (`email`)
) ENGINE = MYISAM
So, I'm not sure that the way I retrieve data is correct or not.. the position attribute is either user or staff.
I'm trying to code a simple randomizer app. I had the randomizer button working, but then I changed some code (which I thought was irrelevant to the randomizer button) and it started crashing and getting the "IllegalStateException: Could not execute method of the activity" error. From what I can tell, this error is very specific to what the code is, because I could not find any answers that fit my code.
package com.example.randomgamechooser;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
}
public void chooseGame (View view) {
GameList dbUtil = new GameList(this);
dbUtil.open();
String string = dbUtil.getRandomEntry();
//TextView textView = new TextView(this);
TextView textView = (TextView) findViewById(R.id.chosenbox);
textView.setTextSize(40);
textView.setText(string);
//setContentView (textView);
dbUtil.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen, menu);
return true;
}
//starts the Game Selection activity
public void openGames (View view) {
Intent intent = new Intent(this, GameSelction.class);
startActivity(intent);
}
}
And this is the referenced GameList class
package com.example.randomgamechooser;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.Random;
public class GameList {
private static final String TAG = "GameList";
//database name
private static final String DATABASE_NAME = "game_list";
//database version
private static final int DATABASE_VERSION = 1;
//table name
private static final String DATABASE_TABLE = "game_list";
//table columns
public static final String KEY_NAME = "name";
public static final String KEY_GENRE = "genre";
public static final String KEY_ROWID = "_id";
//database creation sql statement
private static final String CREATE_GAME_TABLE =
"create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME +" text not null, " + KEY_GENRE + " text not null);";
//Context
private final Context mCtx;
private DatabaseHelper mDbHelper;
private static SQLiteDatabase mDb;
//Inner private class. Database Helper class for creating and updating database.
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// onCreate method is called for the 1st time when database doesn't exists.
#Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "Creating DataBase: " + CREATE_GAME_TABLE);
db.execSQL(CREATE_GAME_TABLE);
}
//onUpgrade method is called when database version changes.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion);
}
}
//Constructor - takes the context to allow the database to be opened/created
//#param ctx the Context within which to work
public GameList(Context ctx) {
this.mCtx = ctx;
}
//This method is used for creating/opening connection
//#return instance of GameList
//#throws SQLException
public GameList open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
//This method is used for closing the connection.
public void close() {
mDbHelper.close();
}
//This method is used to create/insert new game.
//#param name
// #param genre
// #return long
public long createGame(String name, String genre) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_GENRE, genre);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
// This method will delete game.
// #param rowId
// #return boolean
public static boolean deleteGame(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
// This method will return Cursor holding all the games.
// #return Cursor
public Cursor fetchAllGames() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
KEY_GENRE}, null, null, null, null, null);
}
// This method will return Cursor holding the specific game.
// #param id
// #return Cursor
// #throws SQLException
public Cursor fetchGame(long id) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_GENRE}, KEY_ROWID + "=" + id, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public int getAllEntries()
{
Cursor cursor = mDb.rawQuery(
"SELECT COUNT(name) FROM game_list", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
}
public String getRandomEntry()
{
//id = getAllEntries();
Random random = new Random();
int rand = random.nextInt(getAllEntries());
if(rand == 0)
++rand;
Cursor cursor = mDb.rawQuery(
"SELECT name FROM game_list WHERE _id = " + rand, null);
if(cursor.moveToFirst()) {
return cursor.getString(0);
}
return cursor.getString(0);
}
// This method will update game.
// #param id
// #param name
// #param standard
// #return boolean
public boolean updateGame(int id, String name, String standard) {
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_GENRE, standard);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + id, null) > 0;
}
}
and here is the error log
07-31 14:50:45.215: D/AndroidRuntime(280): Shutting down VM
07-31 14:50:45.215: W/dalvikvm(280): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
07-31 14:50:45.236: E/AndroidRuntime(280): FATAL EXCEPTION: main
07-31 14:50:45.236: E/AndroidRuntime(280): java.lang.IllegalStateException: Could not execute method of the activity
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View$1.onClick(View.java:2072)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View.performClick(View.java:2408)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View$PerformClick.run(View.java:8816)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.os.Handler.handleCallback(Handler.java:587)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:92)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-31 14:50:45.236: E/AndroidRuntime(280): at dalvik.system.NativeStart.main(Native Method)
07-31 14:50:45.236: E/AndroidRuntime(280): Caused by: java.lang.reflect.InvocationTargetException
07-31 14:50:45.236: E/AndroidRuntime(280): at com.example.randomgamechooser.MainScreen.chooseGame(MainScreen.java:23)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View$1.onClick(View.java:2067)
07-31 14:50:45.236: E/AndroidRuntime(280): ... 11 more
07-31 14:50:45.236: E/AndroidRuntime(280): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.example.randomgamechooser.GameList.getRandomEntry(GameList.java:153)
07-31 14:50:45.236: E/AndroidRuntime(280): ... 15 more
Read the stacktrace carefuly. Answer is at the last "Caused by" exception;
07-31 14:50:45.236: E/AndroidRuntime(280): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.example.randomgamechooser.GameList.getRandomEntry(GameList.java:153)
07-31 14:50:45.236: E/AndroidRuntime(280): ... 15 more
Query in method getRandomEntry() returns empty result, while you read from the first position.
My classmates and I are stuck on an issue with android application we are building.
We've successfully built an Android app which contains an activity which searches our browser histories / bookmarks for specific urls and launches another activity (successfully) if a match is found as an example of an adult content warning implementation.
This is functioning fine.
Now we are implementing a service class to continually execute every few seconds - in order to execute the search of our recent history using our new service class - but we're experiencing a few issues.
Our problem is when we attempt to add the "Nanny" source code from Nanny.java to the service class so the "Nanny" script will search the history continuously, instead of just once - the "Nanny" application continually force closes - due to a null pointer exception at the initialization of our cursor: if (cursor.moveToFirst()) {
Which is a bit strange because the NullPointerException does not occur when the exact same script is executed outside the service class in a test file we have (Main.java)
Our working Main.java and our working service class [which successfully displays a toast every few seconds] as well as our [failed] combination of the two - are shown below:
Empty Service Class:
public class Service_class extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
Working Nanny.java
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Browser;
import android.widget.TextView;
public class Nanny extends Activity {
String Dirty1 = "www.playboy.com";
String Dirty2 = "www.penthouse.com";
String Dirty3 = "www.pornhub.com";
String Dirty4 = "www.playboy.com";
String Dirty5 = "www.playboy.com";
String Dirty6 = "www.playboy.com";
String Dirty7 = "www.playboy.com";
String Dirty8 = "www.playboy.com";
String Dirty9 = "www.playboy.com";
String Dirty10 = "www.playboy.com";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nanny);
TextView tv = (TextView) findViewById(R.id.hello);
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
if (url.toLowerCase().contains(Dirty1)) {
} else if (url.toLowerCase().contains(Dirty2)) {
} else if (url.toLowerCase().contains(Dirty3)) {
} else if (url.toLowerCase().contains(Dirty4)) {
} else if (url.toLowerCase().contains(Dirty5)) {
} else if (url.toLowerCase().contains(Dirty6)) {
} else if (url.toLowerCase().contains(Dirty7)) {
} else if (url.toLowerCase().contains(Dirty8)) {
} else if (url.toLowerCase().contains(Dirty9)) {
} else if (url.toLowerCase().contains(Dirty10)) {
//if (url.toLowerCase().contains(Filthy)) {
urls = urls
+ cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.TITLE)) + " : "
+ url + "\n";
Intent intent = new Intent(Nanny.this, Warning.class);
Nanny.this.startActivity(intent);
}
} while (cursor.moveToNext());
tv.setText(urls);
}}}
Unsuccessful method we've attempted to implement (adding the functioning nanny script to the service class) which causes the NullPointerException: if (cursor.moveToFirst()) {
public class Service_class extends Service {
String Dirty1 = "www.playboy.com";
String Dirty2 = "www.penthouse.com";
String Dirty3 = "www.pornhub.com";
String Dirty4 = "www.playboy.com";
String Dirty5 = "www.playboy.com";
String Dirty6 = "www.playboy.com";
String Dirty7 = "www.playboy.com";
String Dirty8 = "www.playboy.com";
String Dirty9 = "www.playboy.com";
String Dirty10 = "www.playboy.com";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
//setContentView(R.layout.main3);
// TextView tv = (TextView) findViewById(R.id.hello);
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
if (url.toLowerCase().contains(Dirty1)) {
} else if (url.toLowerCase().contains(Dirty2)) {
} else if (url.toLowerCase().contains(Dirty3)) {
} else if (url.toLowerCase().contains(Dirty4)) {
} else if (url.toLowerCase().contains(Dirty5)) {
} else if (url.toLowerCase().contains(Dirty6)) {
} else if (url.toLowerCase().contains(Dirty7)) {
} else if (url.toLowerCase().contains(Dirty8)) {
} else if (url.toLowerCase().contains(Dirty9)) {
} else if (url.toLowerCase().contains(Dirty10)) {
urls = urls
+ cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.TITLE)) + " : "
+ url + "\n";
Intent warning_intent = new Intent(Service_class.this, Warning.class);
Service_class.this.startActivity(intent);
}
} while (cursor.moveToNext());
// tv.setText(urls);
return START_STICKY;
}
return startId;}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
private void setContentView(int main3) {
// TODO Auto-generated method stub
}
private TextView findViewById(int hello) {
// TODO Auto-generated method stub
return null;
}
private Cursor managedQuery(Uri bookmarksUri, String[] projection,
Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
LOGCAT (When using combined implementation shown above)
Fails on Line 53: if (cursor.moveToFirst()) {
04-15 18:26:24.761: D/dalvikvm(7466): Late-enabling CheckJNI
04-15 18:26:25.651: D/dalvikvm(7466): GC_FOR_ALLOC freed 82K, 4% free 7379K/7608K, paused 13ms, total 13ms
04-15 18:26:25.651: I/dalvikvm-heap(7466): Grow heap (frag case) to 10.861MB for 3686416-byte allocation
04-15 18:26:25.661: D/dalvikvm(7466): GC_FOR_ALLOC freed 1K, 3% free 10977K/11212K, paused 13ms, total 13ms
04-15 18:26:25.681: D/dalvikvm(7466): GC_CONCURRENT freed <1K, 3% free 10977K/11212K, paused 3ms+2ms, total 17ms
04-15 18:26:25.901: D/dalvikvm(7466): GC_FOR_ALLOC freed <1K, 3% free 10977K/11212K, paused 11ms, total 11ms
04-15 18:26:25.911: I/dalvikvm-heap(7466): Grow heap (frag case) to 17.086MB for 6529744-byte allocation
04-15 18:26:25.931: D/dalvikvm(7466): GC_FOR_ALLOC freed 0K, 2% free 17354K/17592K, paused 13ms, total 13ms
04-15 18:26:25.941: D/dalvikvm(7466): GC_CONCURRENT freed <1K, 2% free 17354K/17592K, paused 3ms+2ms, total 16ms
04-15 18:26:26.051: D/libEGL(7466): loaded /system/lib/egl/libEGL_tegra.so
04-15 18:26:26.061: D/libEGL(7466): loaded /system/lib/egl/libGLESv1_CM_tegra.so
04-15 18:26:26.071: D/libEGL(7466): loaded /system/lib/egl/libGLESv2_tegra.so
04-15 18:26:26.091: D/OpenGLRenderer(7466): Enabling debug mode 0
04-15 18:26:31.181: D/AndroidRuntime(7466): Shutting down VM
04-15 18:26:31.181: W/dalvikvm(7466): threadid=1: thread exiting with uncaught exception (group=0x40f4f930)
04-15 18:26:31.181: E/AndroidRuntime(7466): FATAL EXCEPTION: main
04-15 18:26:31.181: E/AndroidRuntime(7466): java.lang.RuntimeException: Unable to start service com.ut.appdemo.Service_class#41698e90 with Intent { cmp=com.ut.appdemo/.Service_class }: java.lang.NullPointerException
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2673)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.access$1900(ActivityThread.java:141)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1331)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.os.Handler.dispatchMessage(Handler.java:99)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.os.Looper.loop(Looper.java:137)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-15 18:26:31.181: E/AndroidRuntime(7466): at java.lang.reflect.Method.invokeNative(Native Method)
04-15 18:26:31.181: E/AndroidRuntime(7466): at java.lang.reflect.Method.invoke(Method.java:511)
04-15 18:26:31.181: E/AndroidRuntime(7466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-15 18:26:31.181: E/AndroidRuntime(7466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-15 18:26:31.181: E/AndroidRuntime(7466): at dalvik.system.NativeStart.main(Native Method)
04-15 18:26:31.181: E/AndroidRuntime(7466): Caused by: java.lang.NullPointerException
04-15 18:26:31.181: E/AndroidRuntime(7466): at com.ut.appdemo.Service_class.onStartCommand(Service_class.java:53)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2656)
04-15 18:26:31.181: E/AndroidRuntime(7466): ... 10 more
You are setting the cursor to null...
you use this method to instantiate the cursor:
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,projection, null, null, null);
and then you define managedQuery() method like this:
private Cursor managedQuery(Uri bookmarksUri, String[] projection, Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
essentially what your code says is:
Cursor cursor = null;
curser.doSomething();
this will always result in a nullPointer. I strongly suggest you go back and study java fundamentals before diving in to android, you are just asking for headaches if you are trying to accomplish something in android with such a lack of understanding of java.