Android startup dialog remote data - java

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.

Related

Android Eclipse 'Source not found' at execute

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.

Android HttpPost cause the app to crash

I'm trying to send post request to my PHP page through java in android studio
and I tried the same code in eclipse but the same problem show, the app stop working.
I put the permission for the internet in the manifest.
My Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt=(TextView) findViewById(R.id.textView1);
String mail="aa#gmail.com",pass="pass";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2:8888/LoginTest/login.php");
try {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("mail", mail));
nameValuePair.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response= httpClient.execute(httpPost);
InputStream is= response.getEntity().getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
StringBuilder sb=new StringBuilder();
String line=null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
txt.setText(sb.toString());
br.close();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My LogCat : https://www.dropbox.com/s/smhyoxdob66czr7/testLogCat.txt?dl=0
Most probably, your application is crashing due to an exception, that is android.os.NetworkOnMainThreadException
This exception is thrown when you try to do lengthy time consuming tasks like network request and downloading the response on main thread, like you're doing in your onCreate(). Android doesn't like it. It keeps it frozen / un-responsive, which makes it angry and it kills your app.
The solution to use AsyncTask. The idea is to do lengthy tasks in background threads instead of main thread. Like as follow:
//this should be inside your Activity class
private class NetworkRequestTask extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
// your network code here
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// set the result to your label
}
}
and from your onCreate() call this task as follow:
new NetworkRequestTask(). execute();
It'll make android happy and responsive. It'll let your app running and won't kill it.

Toast for invalid login not showing? Android

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.

My Android app needs to verify connection to internet onClick of a button but app is crashing on using my code

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

audio recording and POST to server

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.

Categories

Resources