method didn't work in android - android

I have a problem with my project
here is my LoginActivity
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginActivity extends Activity {
private final Context context = this;
EditText un;
EditText pw,ds;
TextView error;
String i;
String x;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
un=(EditText)findViewById(R.id.un);
pw=(EditText)findViewById(R.id.pwd);
error=(TextView)findViewById(R.id.tv_error);
}
public void clickHandler(View view){
Intent i = null;
switch (view.getId()){
case R.id.btnLogin:
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
/* String valid = "1";*/
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/android/cek.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
error.setText(res);
if (res.equals("1")){
i = new Intent (this, Menu.class);
startActivity(i);
} else {
error.setText("Sorry!! Username or Password salah");
}
} catch (Exception e) {
un.setText(e.toString());
}
break;
case R.id.registerBtn:
i = new Intent(this, RegisterActivity.class);
startActivity(i);
break;
case R.id.btnExit:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Keluar dari aplikasi ini?");
builder.setCancelable(false);
builder.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Create and show the dialog
builder.show();
break;
}
}
public String uname(){
x = un.getText().toString();
return x;
}
}
and here is my KirimInfo.java
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
public class KirimInfo extends Activity {
String time,date,type,jln,y;
EditText usrn,ket,ds;
Spinner nj,st1;
TextView error;
String[] jalan = {"A.Yani","Ambengan", "Anjasmoro","Baliwerti","Basuki Rahmat","Bintoro","Ciliwung","Darmo Raya","Darmokali","Diponegoro Raya","Dharmawangsa","Dinoyo","Embong Kemiri","Embong Malang"};
String[] stat = {"Macet Total", "Padat", "Padat Merayap","Padat Lancar","Lancar","Sepi"};
/** Called when the activity is first created. */
LoginActivity l = new LoginActivity();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kirim_info);
ket=(EditText)findViewById(R.id.keterangan);
usrn=(EditText)findViewById(R.id.usrnm);
error=(TextView)findViewById(R.id.tv_error3);
nj=(Spinner)findViewById(R.id.namjal);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, jalan);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
nj.setAdapter(aa);
st1=(Spinner)findViewById(R.id.statusKepadatan);
ArrayAdapter<String> bb = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, stat);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
st1.setAdapter(bb);
}
public void clickHandler(View view){
Intent i = null;
switch (view.getId()){
case R.id.btnKirimInfo:
jln = jalan[nj.getSelectedItemPosition()];
type = stat[st1.getSelectedItemPosition()];
String y = l.uname();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", y));
postParameters.add(new BasicNameValuePair("nama_jalan", jln));
postParameters.add(new BasicNameValuePair("keterangan", ket.getText().toString()));
postParameters.add(new BasicNameValuePair("status", type));
/* String valid = "1";*/
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/android/kepadatan.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
error.setText(res);
if (res.equals("1"))
error.setText("Data Berhasil Masuk");
else
error.setText("Gagal");
} catch (Exception e) {
error.setText(e.toString());
}
break;
case R.id.kembali:
i = new Intent(this, Menu.class);
startActivity(i);
break;
}
}
}
I want to send the username from LoginActivity.java to KirimInfo.java. because that I make method "uname" to pass the username.
but when I run the program, it pass empty or NULL even though I have write the username (whereas I have write down username and password correctly from the database)
what I want to ask, am I write the method "uname" correct? can you tell me how to write a correct method and initiate object so I can pass the username?
because I don't know how to make a method and initiate object in android correctly
please tell me how....any help will appreciate
Thank You

LoginActivity l = new LoginActivity();
String y = l.uname();
This is not right procedure for sending value from one activity to Another activity.
Add the following in your program.
in LoginActivity.java add :..
Whaen you call the KirimInfo.java Activity
add
Intent intent = new Intent(LoginActivity.this,KirimInfo.class);
intent.putExtra("username",""+uname());
in KirimInfo actrivity add the following
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String userName = bundle.getString("username");

when you in KirimInfo then you are accessing the UI of LoginActivity in uname() which is not a recommend way to do so.
If you want to transfer data between activities use Bundle
for example
Intent intent = new Intent(LoginActivity.this, KirimInfo.class);
intent.putExtra("USER_NAME", "Safarudin");
startActivity(intent);
and to get data in other activity use like this in OnCreate
String userName=getIntent().getStringExtra("USER_NAME");

Related

While loop or for loop for json object for android not working

I am trying to add a for loop or while loop for method getuserDetailWhileLoop(); but i am having a hard time figuring out on how to do it. This code suppose to show json object to text view and text view has scroll view in it. However when i ran the code the while loop is not working and only show 1 object. I need the while loop to show multiple object. How will i be doing that? Thanks.
package com.demo.myblog.profile;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.demo.myblog.R;
import com.demo.myblog.volley.VolleySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class UserProfile extends AppCompatActivity {
private String ID,NAME,EMAIL,CREATED_DATE, ID2;
private String appURl, appURl2;
Activity mContext = this;
TextView mId,mName,mEmail,mDate, mid2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile2);
mId = findViewById(R.id.txt_Id);
mid2 = findViewById(R.id.textView5);
mName = findViewById(R.id.txt_Name);
mEmail = findViewById(R.id.txt_Email);
mDate = findViewById(R.id.txt_Data);
Intent data = getIntent();
EMAIL = data.getStringExtra("email");
appURl = "url here";
appURl2 = "url2 here";
getUserDetail();
getuserDetailWhileLoop();
}
private void getuserDetailWhileLoop()
{
if (EMAIL.isEmpty()){
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setMessage("Email cannot be empty");
alert.setCancelable(false);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
else{
StringRequest stringRequest = new StringRequest(Request.Method.GET,appURl2, new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try
{
JSONObject jo = new JSONObject( response );
for(int i =0 ;i < jo.length(); i++)
{
ID2 = jo.getString( "id" );
//NAME = jsonObject.getString("username");
//EMAIL = jsonObject.getString("user_email");
//CREATED_DATE = jsonObject.getString("created_date");
//sonObject = jsonObject.getJSONObject( "id" );
mid2.setText( ID2 );
//mName.setText(NAME);
//mEmail.setText(EMAIL);
//mDate.setText(CREATED_DATE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I like to use for loops over while loops, because with a for loop you're able to check the progress of the loop.
In this case it is best to use a for loop, just like you already did.
Can you post a example response of the StringRequest?
[EDIT]
You forgot to add the counter 'i', your for loop is fine.
JSONObject obj = jo.getJSONObject(i);
obj.getString("id");
I think this is the solution to your problem.

how can I send an image using an http request

I am working on an application that would send an image with 2 strings but I am not as experienced in this field so i was lost for the last day or two trying to figure this out as i started with a script but didn't work for me
here is the part of script that i worked on which has a bit PHP behind and just show an image in my activity once it's chosen form the gallery with a bit of logic that i understood but didn't really work for me
that's my java code :
package com.example.tuteur;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class ajouter_photo extends AppCompatActivity implements View.OnClickListener {
ImageView upload_img;
EditText img_text;
EditText img_titre;
Button img_but;
private static final int result_load_img = 1;
private static final String server = "http://192.168.1.3/pfe/saveImg.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ajouter_photo);
upload_img=findViewById(R.id.photo_upload);
img_but=findViewById(R.id.upload_button);
img_text=findViewById(R.id.upload_text_corps);
img_titre=findViewById(R.id.upload_text_title);
upload_img.setOnClickListener(this);
img_but.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case(R.id.photo_upload):
Intent galleryIntent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent,result_load_img);
break;
case(R.id.upload_button):
Bitmap image =((BitmapDrawable) upload_img.getDrawable()).getBitmap();
new uploadimg(img_text.getText().toString(),image,img_titre.getText().toString());
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if( requestCode==result_load_img && resultCode==RESULT_OK && data != null){
Uri selectedimg = data.getData();
upload_img.setImageURI(selectedimg);
}
}
private class uploadimg extends AsyncTask<Void , Void , Void> {
String text;
Bitmap image;
String titre;
public uploadimg(String text, Bitmap image,String titre) {
this.text = text;
this.image = image;
this.titre=titre;
}
#Override
protected Void doInBackground(Void ... params) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100,byteArrayOutputStream);
String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT);
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("text",text));
dataToSend.add(new BasicNameValuePair("image",encodedImage));
dataToSend.add(new BasicNameValuePair("titre",titre));
HttpParams httpRequest = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequest);
HttpPost post =new HttpPost(server);
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"erreur" , Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(getApplicationContext(),"L'image est envoyé",Toast.LENGTH_SHORT).show();
}
}
private HttpParams getHttpRequestParams()
{
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,1000*30);
HttpConnectionParams.setSoTimeout(httpRequestParams,1000*30);
return httpRequestParams;
}
}
and this is my PHP which just store my image in the server not a data base it was test before I would try with blob
<?php
$name = $_POST["text"];
$image=$_POST["image"];
$decodedImage = base64_decode("$image");
file_put_contents("pictures". $name . ".PNG" , $decodedImage);
?>

Asynctask is timing out after 5 minutes [android]

I am running a long running process (which is an servlet call) inside an AsyncTask doInBackground which may run for more than 5 minutes. But after 5 minutes the servlet is returned and I am getting a timeout problem.
Below is my code:
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.example.hanamom.LoginActivity.GetXMLTask;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.ProgressDialog;
public class NewInstallationActivity extends Activity {
Button install;
EditText branch_enter;
EditText cl_enter;
EditText sid_enter;
EditText sidpwd_enter;
EditText systempwd_enter;
EditText instance_enter;
EditText installationlocation_enter;
Bundle extras;
EditText desc_enter;
ProgressDialog pd;
public static final String URL = "<a servlet call>";
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
Intent intent;
String login_user,host,rootuser,rootpassword;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.install);
addListenerOnButton();
Log.e("test", "Entered New Instlalaiton activity");
branch_enter = (EditText) findViewById(R.id.branch_enter);
cl_enter = (EditText) findViewById(R.id.cl_enter);
sid_enter = (EditText) findViewById(R.id.sid_enter);
sidpwd_enter = (EditText) findViewById(R.id.sidpwd_enter);
systempwd_enter = (EditText) findViewById(R.id.systempwd_enter);
instance_enter=(EditText) findViewById(R.id.instance_enter);
installationlocation_enter=(EditText) findViewById(R.id.installationlocation_enter);
Bundle extras = this.getIntent().getExtras();
login_user=extras.getString("login_user").trim();
host = extras.getString("promptshost");
rootuser = extras.getString("lrootUser");
rootpassword = extras.getString("lrootpwd");
Log.e("login user",login_user);
Log.e("rootuser=",rootuser);
Log.e("rootpassword=",rootpassword);
}
private void addListenerOnButton() {
// TODO Auto-generated method stub
final Context context = this;
branch_enter = (EditText) findViewById(R.id.branch_enter);
cl_enter = (EditText) findViewById(R.id.cl_enter);
sid_enter = (EditText) findViewById(R.id.sid_enter);
sidpwd_enter = (EditText) findViewById(R.id.sidpwd_enter);
systempwd_enter = (EditText) findViewById(R.id.systempwd_enter);
instance_enter=(EditText) findViewById(R.id.instance_enter);
installationlocation_enter=(EditText) findViewById(R.id.installationlocation_enter);
install = (Button) findViewById(R.id.install);
install.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
});
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
String response = "false";
private ProgressDialog pd;
protected void onPreExecute() {
pd = new ProgressDialog(NewInstallationActivity.this);
pd.setMessage("Please wait while SAP HANA system is being Installed..");
pd.setIndeterminate(false);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setProgress(0);
pd.show();
}
protected String doInBackground(String... urls) {
try {
Log.e("NewInstallationActivty", "New installation");
String branch=branch_enter.getText().toString();
String cl = cl_enter.getText().toString();
String sid=sid_enter.getText().toString();
String sidpwd=sidpwd_enter.getText().toString();
String systempwd=systempwd_enter.getText().toString();
String instance=instance_enter.getText().toString();
String installationlocation=installationlocation_enter.getText().toString();
Log.e("Branch=",branch);
Log.e("Host=",host);
Log.e("sid=",sid);
Log.e("sidpwd=",sidpwd);
Log.e("systempwd=",systempwd);
Log.e("instance=",instance);
Log.e("installationlocation=",installationlocation);
Log.e("rootuser=",rootuser);
Log.e("rootpassword=",rootpassword);
// String osuser=osuser_enter.getText().toString();
// String ospassword=ospassword_enter.getText().toString();
Log.e("NewInstlalationActivity", "installtion");
postParameters.add(new BasicNameValuePair("branch",branch));
postParameters.add(new BasicNameValuePair("cl", cl));
postParameters.add(new BasicNameValuePair("sid", sid));
postParameters.add(new BasicNameValuePair("sidpwd", sidpwd));
postParameters.add(new BasicNameValuePair("systempwd",systempwd));
postParameters.add(new BasicNameValuePair("instance",instance));
postParameters.add(new BasicNameValuePair("installationlocation",installationlocation));
postParameters.add(new BasicNameValuePair("host",host));
postParameters.add(new BasicNameValuePair("rootuser", rootuser));
postParameters.add(new BasicNameValuePair("rootpassword", rootpassword));
postParameters.add(new BasicNameValuePair("intent","install"));
Log.e("NewInstlalationActivity", "post parameters");
for (String url : urls) {
response = CustomHttpClient.executeHttpPost(url,postParameters);
}
}
catch(Exception e) {}
return "Success";
}
protected void onPostExecute(String output) {
Log.e("Login Activity",response);
while(!response.trim().equals("True"))
{
pd.show();
pd.setProgress(100);
continue;
}
if (response.trim().equals("True"))
{
Log.e("Entered Response = True", response);
pd.dismiss();
Intent intent = new Intent(getBaseContext(), NewInstallationActivity.class);
startActivity(intent);
}
else
{
Log.e("Else code","Else");
AlertDialog alertDialog = new AlertDialog.Builder(
NewInstallationActivity.this).create();
alertDialog.setTitle("Installation Failed!");
// Setting Dialog Message
alertDialog.setMessage(" Check logs at /var/tmp");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
}
}
}
}
Here my process dialog will wait until I get a True from the servlet but exactly after 5 minutes, it is sending a false.
Is there any method to wait for more than 5 minutes. Any hint would be helpful.
Thanks.
You can try the following :
private final static long TIMETOWAIT = 30000; // Set your timeout.
....
GetXMLTask.get(TIMETOWAIT,TimeUnit.MILLISECONDS);
....
For reference :
http://developer.android.com/reference/android/os/AsyncTask.html#get%28long,%20java.util.concurrent.TimeUnit%29

sending data from edit text with single button

![here there are 3 edit text box. where i am using json to check the login id and password details and another text box is for the selection of the server address. the only criteria is that all these should be done with a single button ie the login button.
can any one help me with the code]1
the code is as follows
package com.example.catxam;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.catxam.JSONParser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class Login extends Activity {
private EditText inputUserid, inputPassword, server;
TextView forgotPassword;
private Button b1;
public String serve;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String Flag = "flag";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.login);
inputUserid = (EditText) findViewById(R.id.Username_edit);
inputPassword = (EditText) findViewById(R.id.User_password);
server = (EditText) findViewById(R.id.serverSelection);
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent passForget = new Intent(getApplicationContext(),
ForgotPassword.class);
startActivity(passForget);
}
});
b1 = (Button) findViewById(R.id.loginbutton); // login button
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new CreateNewUser().execute();
new SelectServerAddress().execute();
}
});
}
// this class is for selection of the server address
class SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... arg0) {
return null;
}
}
// this class is for the checking of the user login and password
//i.e. of first login and the next consecutive logins
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Checking..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Checking creditenials
* */
protected String doInBackground(String... args) {
String user = inputUserid.getText().toString();
String pswrd = inputPassword.getText().toString();
//if (serve == "")
//{
//serve = "192.168.0.101/gly_prov_V1";
//}
//else
//{
//serve = "glydenlewis.esy.es";
//}
// URL to check username & password
final String url_check_user = "http://" + serve +"/gly_prov_V1/android_check.php";
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", user));
params.add(new BasicNameValuePair("psd", pswrd));
params.add(new BasicNameValuePair("server",serve));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_check_user,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
int flag_ck = json.getInt(Flag);
if (success == 1) {
if (flag_ck == 0)
{
//First Time Login By User
Intent i = new Intent(getApplicationContext(), UpdateDetails.class);
startActivity(i);
finish(); // closing this screen
}
else
{
// successfully login
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish(); // closing this screen
}
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
You can execute tasks in serial manner. Take the output of first task as input to the second task.
But you have to implement a cancel mechanism if the activity is destroyed while your tasks is actually running. a simple approach is to make tasks references as a class member and cancel it when activity's onStop() method is called.
class static SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... urls) {
return getAddress(urls[0]);
}
#Override
protected void onPostExecute(String serverAddress) {
// Call login service
mLoginTask = new CreateNewUser(serverAddress);
mLoginTask.execute();
}
}
Edit:
Update button click listener code to this:
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new SelectServerAdress().execute();
}
});
Then update SelectServerAdress class and add this method:
#Override
protected void onPostExecute(String serverAddress) {
serve = serverAddress;
new SelectServerAddress().execute();
}

toast mesage not shown on screen when network or server not available

I need to show toast message when the server is not responding
when I press the login button, some parameters are passed to AgAppMenu screen which use url connection to server and get xml response in AgAppHelperMethods screen. The
probelm is when the server is busy or the network is not avaibale, I can't show toast message on catch block although it shows the log message.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginScreen extends Activity implements OnClickListener {
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.agapplogin);
TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources()
.getColor(R.color.text_color_red));
mobile = (EditText) findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText) findViewById(R.id.txtPinNo);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnClear = (Button) findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
cleartext();
}
});
/*
*
* btnClear.setOnClickListener(new OnClickListener() { public void
* onClick(View arg0) {
*
* } });
*/
}
public void postLoginData()
{
if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {
AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
altDialog.setMessage("Please Enter Complete Information!");
} else {
Intent i = new Intent(this.getApplicationContext(), AgAppMenu.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i);
}
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("");
mobile.setText("");
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AgAppMenu extends Activity {
String mno, pinno;
private String[][] xmlRespone;
Button btnMiniStatement;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agappmenu);
mno = getIntent().getExtras().getString("mno");
pinno = getIntent().getExtras().getString("pinno");
setTitle("Welcome to the Ag App Menu");
AgAppHelperMethods agapp =new AgAppHelperMethods();
// xmlRespone = AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
boolean flag = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {
}
public static AgAppHelperMethods getInstance() {
if (instance == null) {
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl() {
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl) {
String _node, _element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
// this "for" loop is used to parse through the
// XML document and extract all elements and their
// value, so they can be displayed on the device
for (int i = 0; i < list.getLength(); i++) {
Node value = list.item(i).getChildNodes().item(0);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}// end for
throw new ArrayIndexOutOfBoundsException();
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Toast.makeText(AgAppHelperMethods.this,
"error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
// Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
return xmlRespone;
}
`
AgAppHelperMethods isn't really an Activity. You've derived this class from Activity, but then you've created Singleton management methods (getInstance()) and you are instantiating it yourself. This is bad. Don't do this.
Normally Android controls the instantiation of activities. You don't ever create one yourself (with new).
It looks to me like AgAppHelperMethods just needs to be a regular Java class. It doesn't need to inherit from anything. Remove also the lifecycle methods like onCreate().
Now you will have a problem with the toast, because you need a context for that and AgAppHelperMethods isn't a Context. To solve that you can add Context as a parameter to AgAppXMLParser() like this:
public String[][] AgAppXMLParser(Context context, String parUrl) {
...
// Now you can use "context" to create your toast.
}
When you call AgAppXMLParser() from AgAppMenu just pass "this" as the context parameter.

Categories

Resources