I've a problem in Eclipse while coding an Android App..
If I'm in debug mode and go line-by-line through my code I get an error with the Message "Source not found".
Here is my Code:
public boolean checkVersion(){
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://"+this.ip+"/fastorder/android/checkDatabaseVersion.php"); // make sure the url is correct.
try{
String db_vers = String.valueOf(DATABASE_VERSION);
//add your data
nameValuePairs = new ArrayList<NameValuePair>();
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("version", db_vers)); // $Edittext_value = $_POST['Edittext_value'];
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
//response = httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response: " + response);
if(response.equalsIgnoreCase("true")){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Speisekarte aktualisieren?");
// set dialog message
alertDialogBuilder
.setMessage("Wollen Sie jetzt die aktuelle Version der Speisekarte downloaden?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
loadUpdate();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
else if(response.equalsIgnoreCase("false")){
}
}catch(ClientProtocolException e){
Log.e("FastOrder", "Exception : " + e);
}catch(IOException e){
Log.e("FastOrder", "Exception : " + e);
}
return true;
}
the error apears in: String response = httpclient.execute(httppost, responseHandler); line...
Anyone has an answer? I try to fix this since days...
This happens because the source code for the method you are trying to access cannot be found.
Try pressing [F6] at the line where you get the error.
Related
I'm making a login app with android. I'm trying to show a dialog that shows up whenever I enter an invalid credentials but it's not working? what Am i doing wrong?
I am able to log in fine though I just need the error toast
Code snippet
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "",
"Validating your Account", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.3.2/sunshine-ems/login.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",inputUsername.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",inputPassword.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
String username = inputUsername.getText().toString().trim();
switch(Integer.parseInt(response)){
case 0:
session.createLoginSession(username);
Intent b = new Intent(MainActivity.this, Profile.class);
startActivity(b);
finish();
break;
default:
Toast.makeText(MainActivity.this,"Invalid username or password.", Toast.LENGTH_LONG).show();
break;
}
dialog.dismiss();
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
}
Logcat for invalid input
01-01 14:16:37.179: W/audio_hw_primary(111): out_write() limiting sleep time 32244 to 23219
01-01 14:16:47.699: W/audio_hw_primary(111): out_write() limiting sleep time 44149 to 23219
01-01 14:16:47.711: W/SingleClientConnManager(1571): Invalid use of SingleClientConnManager: connection still allocated.
01-01 14:16:47.711: W/SingleClientConnManager(1571): Make sure to release the connection before allocating another one.
01-01 14:16:47.723: W/EGL_emulation(1571): eglSurfaceAttrib not implemented
01-01 14:16:47.723: W/audio_hw_primary(111): out_write() limiting sleep time 55759 to 23219
01-01 14:16:47.747: I/System.out(1571): Exception : Invalid int: ""
01-01 14:16:47.755: W/audio_hw_primary(111): out_write() limiting sleep time 27369 to 23219
01-01 14:16:47.927: W/InputMethodManagerService(472): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#53241ec4 attribute=null, token = android.os.BinderProxy#533337e4
01-01 14:16:47.931: W/audio_hw_primary(111): out_write() limiting sleep time 25917 to 23219
You are trying to update UI from a background thread.It is not possible.
Use AsyncTask . Check login details in doInBackground(). Show the Toast/AlertDialogue in onPostExecute().
Here is a nice example to learn the usage of AsyncTask
add this to you activity
private class Login extends AsyncTask<Void,Void,Void>{
private int result=9;
#Override
protected Void doInBackground(Void... params) {
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.3.2/sunshine-ems/login.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",inputUsername.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",inputPassword.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
result=Integer.parseInt(response);
return null;
}catch (Exception e){
System.out.println("Exception : " + e.getMessage());
return null;
}
}
#Override
protected onPostExecute(){
switch(Integer.parseInt(response)){
case 0:
session.createLoginSession(username);
Intent b = new Intent(MainActivity.this, Profile.class);
startActivity(b);
finish();
break;
default:
Toast.makeText(MainActivity.this,"Invalid username or password.", Toast.LENGTH_LONG).show();
break;
}
}
}
and this to you onResume or onCreate
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "",
"Validating your Account", true);
new Login().execute()
}
});
and read about the AsyncTask in Official docs and a tutorial.
I need to verify the internet connection while pressing log-out button in my app and it must show a toast message "connection error" if connection is not present and must not go to the login page.
Following is the error code that i had received in the console window while running the emulator.
Android Runtime Errors:
Fatal Exception: thread -85
java.lang.RuntimeException: Can't create handler inside thread.
I had created a class called "appstatus.java" and used it and working fine with the login page but while i try to use same if else condition with the "mainactivity.java" where logout button is present. its not working and app crashes. below is my code:-
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (AppStatus.getInstance(getBaseContext()).isOnline(getBaseContext())) {
//
Log.v("driver-id from logout:",""+drv_id);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(ServerConnection.ip+"LogoutFlag.jsp");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
Log.v("drv id from logout:",""+drv_id);
nameValuePairs.add(new BasicNameValuePair("driver_id", ""+drv_id));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
String reverseString = response.trim();
Log.v("Response device id from logout",reverseString);
}
catch (Exception e) {
Log.e("logout error:",e.toString());
}
}
else {
Toast.makeText(getBaseContext(), "Connection Lost", Toast.LENGTH_SHORT).show();
}
}
}).start();
I had used same if, else condition to check internet connectivity on the login page and is working fine. here the only difference i notice is a try catch method is used.
My question is:-
Why the app is crashing with above code?
How to rewrite the code avoiding errors for the above mentioned cause?
Any piece of code is highly appreciated and thanks in advance.
Try this way,hope this will help you to solve your problem
Follow few steps to check internet connection and make code without crashes
Step 1. make this method, for checking connection is available or not
void isConnectedToInternet() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null)
greenFlag();
else
new AlertDialog.Builder(activity)
.setTitle("Network connection error !")
.setMessage("Please check internet settings to continue.")
.setNegativeButton("Continue",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
isConnectedToInternet();
}
}).show();
}
Step 2. Run this method on oncreate,
isConnectedToInternet();
Step 3. In this mehtod you need to put all data related to webservices and others task,
void greenFlag() {
// Anything you want to do here
}
thanks
For starters i'm an Android newbie. I have an android application that records audio for 12 seconds to a raw file and then I use lame to convert it to the final file "mezzo.mp3". The application should then upload the file to a server. However, it seems the code never executes to the upload part. Here is my code.
MainActivity.java
class UploadFileTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String responseString = "";
try {
String url = "http://178.62.209.46:8000/api/tag/";
File track = new File(Environment.getExternalStorageDirectory(), "mezzo.mp3");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//InputStream inputStream = new ;
reqEntity.addBinaryBody("track", track);
final HttpEntity myEntity = reqEntity.build();
httppost.setEntity(myEntity);
HttpResponse response = httpclient.execute(httppost);
//process response
responseString = new BasicResponseHandler().handleResponse(response);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
protected void onPostExecute(String responseString){
Toast.makeText(getApplicationContext(), responseString, Toast.LENGTH_LONG).show();
}
}
and here is the timer and the UploadFileTask invocation:
Button startButton = (Button) findViewById(R.id.StartButton);
startButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mRecMicToMp3.start();
CountDownTimer countDowntimer = new CountDownTimer(12000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
mRecMicToMp3.stop();
Toast.makeText(getApplicationContext(), "Stopped recording Automatically ", Toast.LENGTH_LONG).show();
}};countDowntimer.start();
}
});
new UploadFileTask().execute();
The timer runs okay and the "Stopped recording Automatically " toast shows. However, it seems new UploadFileTask().execute();never runs.
What mistake i'm I making??
You posted way to much code. You are supposed to post only relevant code. That in onClick would have been sufficient.
You have a NetworkOnMainThreadException. This will also be clearly visible in the LogCat. You have to put the 'internet code' in an AsyncTask or Thread.
Update: Hmmmm... mayby i talked to soon. Honestly i do not know if code in 'onFinish' is executed on the main thread. But if the Toast comes through it is. Please look in the LogCat for real errors.
You are starting your asynctask at the moment you install an onclicklistener. So even before the user has clicked. You should start it when the recording is done. Place that line directly after the toast that tells that the recording is stopped.
I'm trying to show a dialog box with some remote data when the app starts (welcome message). for some reason this is not working. my code is this.
p.s. I have another progress type dialog which loads at start up. I'm trying to add this just after it.
Could anyone tell if this snippet is correct?
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.website.com/welcome.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id", url));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//String url=response;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My Title");
builder.setMessage(response);
builder.setPositiveButton("OK", null);
AlertDialog dialog = builder.show();
TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
} catch (ClientProtocolException e) {
//Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
} catch (IOException e) {
//Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
}
best test you can do what happend this code dos not work is :
try write e.printStackTrace(); between catch like :
try {
...
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
to know waht happend.
also i think you get error that you cannot access io operation in ui thread, and you must call this method in other thread LIKE :
private void MyMethod() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.website.com/welcome.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id", url));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
//String url=response;
runOnUiThread(
new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My Title");
builder.setMessage(response);
builder.setPositiveButton("OK", null);
AlertDialog dialog = builder.show();
TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
}
}
);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and when want to call this method :
new Thread(new Runnable() {
#Override
public void run() {
MyMethod();
}
}).start();
What is meaning of sentence "for some reason this is not working."? Am I correct when I say dialog doesn't appear?
There's problem with httpclient.execute(). If there is some problem with internet connection, dialog isn't created, because inception has been thrown. Can you see some warning/error in Logcat?
You can't do connection operations in UI Thread, otherwise NetworkOnMainThreadException is thrown.
I'm going to say no - the snippet is not correct. Since API 11 all IO functions need to happen on a background thread. Background threads cannot touch the UI. As it currently stands you are executing an HttpPost within the same method as you are creating an AlertDialog. What you need to do is use an AsyncTask to (1) execute the post in the doInBackground method (2) return the result (3) use the returned result within the onPostExecute method to load your dialog (returning values from doInBackground will automatically send it to onPostExecute). onPostExecute runs on the UI thread so you can create an AlertDialog from that method.
When updating values into database, instead of updating 1 row each time(which is what we wanted), it update the whole database column.
Here are my codes:
Java code:
private Dialog alertDialog() { final AlertDialog.Builder
alertDialog = new AlertDialog.Builder(NotificationActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Confirmation...");
// Setting Dialog Message
alertDialog.setMessage("Do you want to accept this job?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.ic_dialog_alert);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "Accept", Toast.LENGTH_SHORT).show();
// Return Result from alertdialog to database
result = "accepted";
System.out.println("The result is "+ result);
new UpdateActivity().execute();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "Reject", Toast.LENGTH_SHORT).show();
dialog.cancel();
// Return Result from alertdialog to database
result = "rejected";
System.out.println("The result is "+ result);
new UpdateActivity().execute();
}
});
return alertDialog.show(); }
/** * Background Async Task to update database * */ class
UpdateActivity extends AsyncTask {
/** * Before starting background thread Show Progress Dialog * */
#Override protected void onPreExecute() { super.onPreExecute();
pDialog = new ProgressDialog(NotificationActivity.this);
pDialog.setMessage("Sending ...");
pDialog.setIndeterminate(false); pDialog.setCancelable(true);
pDialog.show(); }
/** * Saving product * */ protected String
doInBackground(String... args) {
System.out.println("Sending...");
// getting updated data from dialog String confirmation =
result.toString();
System.out.println("Result to string..." + confirmation );
// Building Parameters List<NameValuePair> params = new
ArrayList(); params.add(new BasicNameValuePair(TAG_ID,
uid)); params.add(new BasicNameValuePair(TAG_RESULT, confirmation));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(UPDATE_URL,
"POST", params);
System.out.println("Json parsing...");
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
System.out.println("Checking...");
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), JobsAcceptedActivity.class);
startActivity(i);
//Toast.makeText(getApplicationContext(), "Update successfully...", Toast.LENGTH_SHORT).show();
System.out.println("Successfully updated...");
// closing this screen
finish();
} else {
// failed to create product
//Toast.makeText(getApplicationContext(), "Update unsucessfully...", Toast.LENGTH_SHORT).show();
System.out.println("Update unsuccessfully...");
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Done!");
return null; }
/**
* After completing background task Dismiss the progress dialog
* **/ protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss(); }
} }
PHP code:
$response = array(); // check for required fields if
(isset($_POST['UID']) && isset($_POST['accept'])) {
$UID = $_POST['UID'];
$accept = $_POST['accept'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("UPDATE notification SET accept = '$accept' WHERE UID = $UID");
// check if column inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Notification successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
} } else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
Q: When updating values into database, instead of updating 1 row each time(which is what we wanted), it update the whole database column.
A: It sounds like you probably want a more restrictive "where" clause on your update :)
This is your one ==> $result = mysql_query("UPDATE notification SET accept = '$accept' WHERE UID = $UID");
My Suggession ==> $result = mysql_query("UPDATE notification SET accept = '$accept' WHERE UID = '$UID'"); or
$queryString= "UPDATE notification SET accept = ".$accept." WHERE UID =".$UID;
$result = mysql_query($queryString);