Disable a Button when Activity Start - android

I have some value Associated to my button Which is linked with the specific field in the my database.
How to disable the button (Without Clicking) if the field is not Null.
I tried to do this :
public class MainActivity extends AppCompatActivity {
Button button;
String service_id = "65";
String indate = "29/03/2018";
String intransit = "2018-03-21 15:00:00.000";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
button = (Button) findViewById( R.id.Enter );
button.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
new Background().execute();
//new Enter().execute();
}
} );
}
private class Background extends AsyncTask<String, Void, String>{
String url;
#Override
protected String doInBackground(String... strings) {
url = "http://localhost/check.php";
try {
URL urL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urL.openConnection();
conn.setRequestMethod( "POST" );
conn.setDoInput( true );
conn.setDoOutput( true );
OutputStream out = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( out, "UTF-8" ) );
String data = URLEncoder.encode( "service_id", "UTF-8" ) + "=" + URLEncoder.encode( service_id, "UTF-8" ) + "&"
+ URLEncoder.encode( "indate", "UTF-8" ) + "=" + URLEncoder.encode( indate, "UTF-8")+ "&"
+ URLEncoder.encode( "intransit", "UTF-8" ) + "=" + URLEncoder.encode( intransit, "UTF-8");
writer.write( data );
writer.flush();
writer.close();
out.close();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader( new InputStreamReader( in, "iso-8859-1" ) );
String result = "";
String line = "";
while((line =reader.readLine()) != null){
result += line;
}
reader.close();
in.close();
conn.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result){
Log.e(TAG, "Result ="+result);
if(result.equals( "Disabled" )){
button.setEnabled( false );
}else{
Toast.makeText( MainActivity.this, "Updated", Toast.LENGTH_SHORT ).show();
button.setEnabled( false );
}
}
}
}
In this code :
Here when the Activity start the button is still enable and to disable it i have to click on it.
Please bare my English.
Thanks For any Help.

Android provides two ways to achieve the same -
1. button.setClickable(false)
Button will not respond to any click events if you use this.
2. button.setEnabled(false)
Using this is not only not clickable, but it also visually indicates that button is disabled.
And based on your null check(condition) you can easily achieve this.
Thanks.

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
button = (Button) findViewById( R.id.Enter );
if(field != null) {
button.setEnabled(false); // Or use setClickable(false) if you still want to show the button as not opaque
}
button.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
new Background().execute();
//new Enter().execute();
}
} );
}
A better practise is to hide the button instead disabling it but I don't know what you have to do, so use the code above

Related

Populate spinner using mysql in android

I am trying get the dropdown list item from my database in my RecyclerView but whenever i try loading me recyclerView Activity the app crashes.
Code Form my RecyclerView Adapter :
public class Register_Adapter extends RecyclerView.Adapter<Register_Adapter.MyHolder> {
//Line number 40
private Context context;
List<dataRegComplaint> data = Collections.emptyList();
List<productlist> data1 = new ArrayList<>( );
Spinner product;
String total;
public static final int CONNECTION_TIMEOUT = 100000;
public static final int READ_TIMEOUT = 150000;
View v;
public Register_Adapter(complaintReg complaintReg,List<dataRegComplaint> data) {
this.context = complaintReg;
this.data = data;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.container_register, viewGroup, false);
return new MyHolder( v );
//Line number 60
}
#Override
public void onBindViewHolder(#NonNull MyHolder myHolder, int i) {
final dataRegComplaint current=data.get(i);
myHolder.client.setText(current.getClientName());
myHolder.location.setText("Location: " + current.getAddress());
myHolder.category.setText("Reason: " + current.getCategory());
myHolder.locationid = current.getlocationid();
myHolder.complaint_register.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
total = current.getlocationid();
Log.e( TAG,"Location id :"+total );
context.startActivity( new Intent( context, Register_New_Complaint.class ) );
}
} );
}
#Override
public int getItemCount() {
return data.size();
}
public class MyHolder extends RecyclerView.ViewHolder{
TextView client,location,category;
Button complaint_register;
String locationid;
public MyHolder(#NonNull View itemView) {
super( itemView );
client = (TextView) itemView.findViewById( R.id.textclient );
location = (TextView) itemView.findViewById( R.id.textlocation );
product = (Spinner) itemView.findViewById( R.id.textproduct1 );
category = (TextView) itemView.findViewById( R.id.textcategory );
complaint_register = (Button) itemView.findViewById( R.id.button_register );
product.setOnItemSelectedListener( (AdapterView.OnItemSelectedListener) context );
}
//Line number 105
}
private class GetProduct extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
HttpURLConnection conn;
URL url = null;
try {
url = new URL( "http://100.98.115.205:8089/productlist.php" );
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( READ_TIMEOUT );
conn.setConnectTimeout( CONNECTION_TIMEOUT );
conn.setRequestMethod( "POST" );
conn.setDoOutput( true );
OutputStream outputStream = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter( outputStream, "UTF-8" ) );
String post_data = URLEncoder.encode( "total", "UTF-8" ) + "=" + URLEncoder.encode(total, "UTF-8" );
Log.e( TAG, "POST DATAv :"+post_data );
bufferedWriter.write( post_data );
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader( new InputStreamReader( input ) );
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append( line );
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute( result );
Log.e( TAG, "RESULT :" +result );
try {
JSONArray jArray = new JSONArray( result );
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject( i );
productlist fishData = new productlist(
json_data.getString( "prod_name" ) );
data1.add( fishData );
Log.e( TAG, "DATA reesult :" +fishData );
}
populateSpinner();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for(int i = 0; i < data1.size(); i++){
lables.add( data1.get( i ).getSiteid());
Log.e( TAG, "Spinner :" +lables.add( data1.get( i ).getSiteid()) );
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>( context,android.R.layout.simple_spinner_dropdown_item, lables );
spinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
product.setAdapter( spinnerAdapter );
}
}
LogCat :
java.lang.ClassCastException: nikhil.loginapp.com.complaintReg cannot be cast to android.widget.AdapterView$OnItemSelectedListener
at nikhil.loginapp.com.Register_Adapter$MyHolder.<init>(Register_Adapter.java:105)
at nikhil.loginapp.com.Register_Adapter.onCreateViewHolder(Register_Adapter.java:60)
at nikhil.loginapp.com.Register_Adapter.onCreateViewHolder(Register_Adapter.java:40)
I am getting my data in my PostExecute function but after that its showing error in Spinner and app crashes.
Some one help me out.

Asynctask not updating TextView in Fragment (Android)

Currently, I am working on a project, where I have to use an Asynctask on multiple fragments. To start with, have I segregated the Asynctask from a Fragment java class, and I have created a new public Java class, where i've put the Asynctask. So far, everything works except the last part (and most important part), where the Asynctask needs to update the textviews on the fragment view.
This is the fragment Java class:
public class DataTabelFragment extends Fragment {
public TextView sensor1;
jsonAsynctask jsonasynctask = new jsonAsynctask(this);
public DataTabelFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate( R.layout.fragment_data_tabel, container, false );
sensor1 = (TextView) view.findViewById( R.id.sensor1Box );
new jsonAsynctask(this).execute();
System.out.println("HEJ MED DIG");
return view;
}
public void inExecute() {
for (int i = 0; i < jsonasynctask.allId.size(); i++) {
sensor1.append( jsonasynctask.allId.get( i ) + " | " + jsonasynctask.allDevice.get( i ) + " | " + jsonasynctask.allTemp.get( i ) + " | " + jsonasynctask.allHum.get( i ) + " | " + jsonasynctask.allBat.get( i ) + " | " + jsonasynctask.allMode.get( i ) + " | " + jsonasynctask.allLux.get( i ) + " | " + jsonasynctask.allDate_time.get( i ) + "\n\n" );
}
}
}
This is the Java Class where in the Asynctask is:
public class jsonAsynctask extends AsyncTask<Void, Void, Void> {
DataTabelFragment dataTabelFragment;
JSONObject idArray, deviceArray, tempArray, humArray, batArray, modeArray, date_timeArray, luxArray;
JSONArray json2;
String basicAuth, line, json_string, json, cxwebURL, credentials, password, username;
String data = "";
String id = "";
List<String> allId = new ArrayList<String>();
List<String> allDevice = new ArrayList<String>();
List<String> allTemp = new ArrayList<String>();
List<String> allHum = new ArrayList<String>();
List<String> allBat = new ArrayList<String>();
List<String> allMode = new ArrayList<String>();
List<String> allDate_time = new ArrayList<String>();
List<String> allLux = new ArrayList<String>();
Gson gson;
ProgressDialog pd;
//HttpsURLConnection connection;
HttpURLConnection connection;
BufferedReader bufferedReader;
URL url;
public jsonAsynctask(DataTabelFragment dataTabelFragment) {
this.dataTabelFragment = dataTabelFragment;
}
public void inBackground() {
username = "xxx";
password = "xxx";
credentials = username + ":" + password;
cxwebURL = "https://" + credentials + "#xxx.com/fetch.php?";
try {
url = new URL( cxwebURL );
connection = (HttpsURLConnection) url.openConnection();
basicAuth = "Basic " + new String( encodeBase64URLSafeString( credentials.getBytes() ) );
connection.setRequestProperty( "Authorization", basicAuth );
connection.setRequestMethod( "GET" );
connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
connection.setRequestProperty( "Content-Language", "en-US" );
connection.setUseCaches( false );
connection.setDoInput( true );
connection.setDoOutput( true );
connection.connect();
InputStream stream = connection.getInputStream();
bufferedReader = new BufferedReader( new InputStreamReader( stream ) );
line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
System.out.println( "PRINT DATA HER: " + data );
json2 = new JSONArray( data );
System.out.println( "DET HER ER json2" + json2 );
for (int i = 0; i < json2.length(); i++) {
idArray = json2.getJSONObject( i );
deviceArray = json2.getJSONObject( i );
tempArray = json2.getJSONObject( i );
humArray = json2.getJSONObject( i );
batArray = json2.getJSONObject( i );
modeArray = json2.getJSONObject( i );
date_timeArray = json2.getJSONObject( i );
luxArray = json2.getJSONObject( i );
id = idArray.getString( "id" );
String temp = tempArray.getString( "temp" );
String device = deviceArray.getString( "device" );
String hum = humArray.getString( "hum" );
String bat = batArray.getString( "bat" );
String mode = modeArray.getString( "mode" );
String date_time = date_timeArray.getString( "time" );
String lux = luxArray.getString( "light" );
allId.add( id );
allDevice.add( device );
allTemp.add( temp );
allHum.add( hum );
allBat.add( bat );
allMode.add( mode );
allDate_time.add( date_time );
allLux.add( lux );
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
private static String encodeBase64URLSafeString(byte[] binaryData) {
return android.util.Base64.encodeToString( binaryData, android.util.Base64.URL_SAFE );
}
#Override
protected Void doInBackground(Void... voids) {
inBackground();
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//pd = new ProgressDialog( new MainActivity() );
//pd.setMessage( "Være sød at vente" );
//pd.setCancelable( false );
//pd.show();
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute( result );
/*
if (pd.isShowing()) {
pd.dismiss();
}*/
gson = new Gson();
json = gson.toJson( data );
json_string = data;
dataTabelFragment.inExecute();
}
}
it is a bad usage of asynctask in your example. In addition, don't hold your data in your asynctask class to retrieve from a fragment. Instead, you should pass your data from onPostExecute method of asynctask to the fragment. The best way is to use an asynctask would be use it with an interface and pass data via that interface. I will put an example, i hope it helps.
public class YourFragment extends Fragment implements YourAsyncTask.YourInterface {
public YourFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_your, container, false);
//do your initial things
.
.
.
YourAsyncTask yourAsyncTask = new YourAsyncTask(this);
yourAsyncTask.execute();
return view;
}
#Override
public void onJobFinishListener(YourDataType yourData) {
//when this method is trigered by your asynctask
//it means that you are in ui thread and update your ui component
//TODO: update ui component with your data
}
}
and below is an asynctask example witn an interface parameter:
public class YourAsyncTask extends AsyncTask {
private YourInterface yourInterfaceListener;
private YourDataType yourData; //this data should be calculated in doInBackground method and send via interface
public YourAsyncTask(YourInterface yourInterfaceListener) {
this.yourInterfaceListener = yourInterfaceListener;
}
#Override
protected Object doInBackground(Object[] objects) {
//do your all background tasks here
.
.
.
yourData = do something here to fill your data..
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
yourInterfaceListener.onJobFinishListener(yourData);
}
public interface YourInterface{
void onJobFinishListener(YourDataType yourData);
}
}
Edit: I didn't see above answer when i was writing this. It s also a nice example
Better make use of Interface.
I have also used in one of my project for almost same scenario.
1) Create Interface
public interface AsyncResponse {
void processFinish(String output);
}
2) Initialise interface in constructor of Async task class like you doing
public jsonAsynctask(AsyncResponse asynctaskResponse) {
this.asynctaskResponse = asynctaskResponse;
}
3) Implement interface in your fragment
new jsonAsynctask(new jsonAsynctask.AsyncResponse() {
#Override
public void processFinish(String output) {
// do whatever you want do here
}
}).execute(videouri.toString(), f.getPath());
Hope It will help.
The interface approach solution example by parliament is the best approach. I would also suggest to use a WeakReference on the private YourInterface yourInterfaceListener;
public class YourAsyncTask extends AsyncTask {
private WeakReference<YourInterface> yourInterfaceListener;
private YourDataType yourData; //this data should be calculated in doInBackground method and send via interface
public YourAsyncTask(YourInterface yourInterfaceListener) {
this.yourInterfaceListener = new WeakReference<YourInterface>(yourInterfaceListener);
}
#Override
protected Object doInBackground(Object[] objects) {
//do your all background tasks here
.
.
.
yourData = do something here to fill your data..
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
if(yourInterfaceListener.get()!=null){
yourInterfaceListener.get().onJobFinishListener(yourData);
}
}
public interface YourInterface{
void onJobFinishListener(YourDataType yourData);
}
}

Pull down to refresh in RecyclerView [duplicate]

This question already has answers here:
Pull to refresh recyclerview android
(7 answers)
Closed 4 years ago.
Bear my English
Whenever any data is added in my database then on refresh the data should be reflected.
And one more thing can you help me Regarding how do I create notification if any new data is Added
I am using:
1) Xampp for Apache
2) Microsoft SQL Server
This is my RecyclerActivtiy
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_engineer_recycler );
Bundle bundle = getIntent().getExtras();
service_id = bundle.getString( "empid" );
type_id = bundle.getString( "type" );
if(type_id.equals( "pending" )){
this.setTitle( "Pending Complaint " );
}else if(type_id.equals( "history" )){
this.setTitle( "Complaint History" );
}
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat( "dd/MM/yyyy" );
String time = format.format( calendar.getTime() );
Log.e( TAG, "Time" +time );
new AsyncLogin().execute(service_id,type_id, time);
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdloding = new ProgressDialog(EngineerRecycler.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute(){
super.onPreExecute();
pdloding.setMessage( "\tLoading.." );
pdloding.setCancelable( false );
pdloding.show();
}
#Override
protected String doInBackground(String... strings) {
try {
serviceid = (String) strings[0];
typeid = (String) strings[1];
time1 = (String) strings[2];
if(typeid.equals( "pending" )){
url = new URL("http://localhost/players.php");
}else if(typeid.equals( "history" )){
url = new URL("http:/localhost/StudentDetails.php");
}
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream outputStream = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter( outputStream, "UTF-8" ) );
String post_data = URLEncoder.encode( "serviceid","UTF-8" ) + "=" + URLEncoder.encode( serviceid, "UTF-8" ) + "&"
+URLEncoder.encode( "time1","UTF-8" ) + "=" + URLEncoder.encode( time1, "UTF-8" );
bufferedWriter.write( post_data );
bufferedWriter.flush();
bufferedWriter.close();
Log.e( TAG, "POST DATA "+post_data );
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result){
Log.e( TAG,"result"+result );
pdloding.dismiss();
List<DataComplaint> data = new ArrayList<>( );
pdloding.dismiss();
if(result.equals( "No complaint assgin null" )){
Toast.makeText( EngineerRecycler.this, "No Complaint Assign", Toast.LENGTH_SHORT ).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
DataComplaint fishData = new DataComplaint(
json_data.getString("comp_desc"),
json_data.getString("comp_reason"),
json_data.getString("ClientName"),
json_data.getString( "SiteName" ),
json_data.getString( "comp_ticketid" ));
data.add(fishData);
}
cAdapter.notifyDataSetChanged();
// Setup and Handover data to recyclerview
complaints = (RecyclerView)findViewById(R.id.complaintList);
cAdapter = new complaintAdapter(EngineerRecycler.this, data,service_id, type_id);
complaints.setAdapter(cAdapter);
complaints.setLayoutManager(new LinearLayoutManager(EngineerRecycler.this));
} catch (JSONException e) {
}
}
}
}
This the code for my Adapter
Code:
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.container_complaint, viewGroup, false);
return new MyHolder( v );
}
#Override
public void onBindViewHolder(#NonNull final MyHolder myHolder, final int i) {
final DataComplaint current=data.get(i);
myHolder.textcomplaint.setText(current.complaint);
myHolder.textaddress.setText("Reason: " + current.getAddress());
myHolder.textType.setText("Client : " + current.getComplaint_type());
myHolder.textplace.setText("Location: " + current.getLocation());
myHolder.textticket.setText( current.getTicket());
myHolder.linearLayout.setVisibility( View.GONE );
}
#Override
public int getItemCount() {
return data.size();
}
public class MyHolder extends RecyclerView.ViewHolder {
TextView textcomplaint;
TextView textaddress;
TextView textType,textplace, textticket, textreso;
Button btn, btn1, btn2;
int value1;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
LinearLayout linearLayout;
RelativeLayout relativeView;
public MyHolder(#NonNull View itemView) {
super( itemView );
textcomplaint = (TextView) itemView.findViewById( R.id.textcomplaint );
textaddress = (TextView) itemView.findViewById( R.id.textaddress );
textType = (TextView) itemView.findViewById( R.id.textType );
textticket = (TextView) itemView.findViewById( R.id.ticketid );
textplace = (TextView) itemView.findViewById( R.id.textplace );
btn = (Button) itemView.findViewById( R.id.enter );
btn1 = (Button) itemView.findViewById( R.id.repositry );
btn2 = (Button) itemView.findViewById( R.id.exit );
linearLayout = (LinearLayout) itemView.findViewById( R.id.linear_layout );
relativeView = (RelativeLayout) itemView.findViewById( R.id.view );
}
Here the problem is how implement pull down to refresh function in my recyclerview.
And Where to write function for it whether in RecyclerActivity or in Adapter.
Can anyone help me out regarding this problem.
You can wrap you RecyclerView with the SwipeRefreshLayout for making a pull to refresh.
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/refreshView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
And you should listen to refresh events for the SwipeRefreshLayout:
refreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Load data to your RecyclerView
refreshData();
}
});

How to send http GET request from my Android app and check the response

I am new in Android development and I need some help with HttpURLConnection.
What I want to do is to send http get request (by clicking button) and then check the response (to check response I added TextView to my main Activity).
My code:
public class MainActivity extends AppCompatActivity {
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendGetRequest(View View) {
new GetClass(this).execute();
}
private class GetClass extends AsyncTask<String, Void, Void> {
private final Context context;
public GetClass(Context c){
this.context = c;
}
protected void onPreExecute(){
progress= new ProgressDialog(this.context);
progress.setMessage("Loading");
progress.show();
}
#Override
protected Void doInBackground(String... params) {
String dataUrl = "http://myurl.com";
String dataUrlParameters = "email="+"pp#gmail.com"+"&name="+"priyabrat";
URL url;
HttpURLConnection connection = null;
try {
final TextView outputView = (TextView) findViewById(R.id.showOutput);
url = new URL(dataUrl);
connection = (HttpURLConnection) url.openConnection();
String urlParameters = "fizz=buzz";
connection.setRequestMethod("GET");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
int responseCode = connection.getResponseCode();
final StringBuilder output = new StringBuilder("Request URL " + url);
output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
output.append(System.getProperty("line.separator") + "Type " + "GET");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder responseOutput = new StringBuilder();
System.out.println("output===============" + br);
while((line = br.readLine()) != null ) {
responseOutput.append(line);
}
br.close();
output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
outputView.setText(output);
progress.dismiss();
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
The problem is, when I run my app and click the button "Send GET Request", application is stopping with message "Application Was stopped"
Have a look at some Networking Librarys for Android, they will handle the async stuff for you:
Volley (https://developer.android.com/training/volley/index.html)
Retrofit makes(HTTP API into a Java interface.)(http://square.github.io/retrofit/)
OkHTTP(Retrofit works with it)https://github.com/square/okhttp/wiki/Recipes
If you would do it for your own, have a look at the doku from Async Task (
https://developer.android.com/reference/android/os/AsyncTask.html) and use the Function:
onPostExecute(String output)
invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
And instead of:
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
outputView.setText(output);
progress.dismiss();
}
});
make this:
return output;

send post data android to php not working [duplicate]

This question already exists:
send post android to php not working [closed]
Closed 9 years ago.
I have a problem I want to send
Email and the name and phone to the server php at the same time
Is there a solution
On which I work is at the bottom
........................................................
public class MainActivity extends Activity {
EditText name;
EditText email;
EditText tlf;
Button btn;
string resultat=null;
InputStream is = null;
StringBuilder sb = null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
name= (EditText)findViewById(R.id.name);
email = (EditText)findViewById(R.id.email);
tlf = (EditText)findViewById(R.id.tlf);
btn = (Button)findViewById(R.id.btn);
}
public void envoyerMessage (View v){
HttpClient client= new DefaultHttpClient();
HttpPost post=new HttpPost("http://xxxxcom/app.php");
String nam = name.getText().toString();
String mail = email.getText().toString();
String fon = tlf.getText().toString();
if(log.length() >0){
try {
List<NameValuePair> donnees = new ArrayList<NameValuePair>(1);
donnees.add(new BasicNameValuePair("id", nam ));
donnees.add(new BasicNameValuePair("mal", mail ));
donnees.add(new BasicNameValuePair("fn", fon ));
post.setEntity(new UrlEncodedFormEntity(donnees));
client.execute(post);
login.setText("");
Toast.makeText(this, "valid login", Toast.LENGTH_SHORT).show();
Thanks
My suggestion is use Volley, here is a very mini sample:
https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java
A Jar to Volley.
But you could try this Util:
public static class Connector extends AsyncTask<String, Object, Object> {
private static final int DEFAULT_CNN_TIME_OUT = 1000 * 20;
private static String USER_AGENT;
private String mUrl;
private byte[] mBody;
public Connector( Context _cxt ) {
super();
if( TextUtils.isEmpty( USER_AGENT ) ) {
// Without this, the default provided by API will be like "Dalvik/1.6.0 (Linux; U; Android 4.0.4; BASE_Lutea_3 Build/IMM76D)" .
USER_AGENT = new WebView( _cxt ).getSettings().getUserAgentString();
}
}
/*
* Convenient function to execute the connecting task.
*/
public void submit( String _url ) {
this.execute( _url );
}
#Override
protected Object doInBackground( String... _params ) {
mUrl = _params[0];
Object ret = null;
HttpURLConnection conn = null;
try {
synchronized( Connector.class ) {
InputStream in = null;
conn = connect( mUrl );
// if we don't do conn.setRequestProperty( "Accept-Encoding", "gzip" ), the wrapper GZIPInputStream can be removed.
onConnectorInputStream( in = new GZIPInputStream( conn.getInputStream() ) );
in.close();
in = null;
}
}
catch( Exception _e ) {
ret = _e;
}
finally {
if( conn != null ) {
conn.disconnect();
conn = null;
}
}
return ret;
}
#Override
protected void onPostExecute( Object _result ) {
if( _result instanceof SocketTimeoutException ) {
onConnectorConnectTimout();
} else if( _result instanceof ConnectorPostConnectException ) {
onConnectorError( ((ConnectorPostConnectException) _result).getStatus() );
} else if( _result instanceof Exception ) {
onConnectorInvalidConnect( (Exception) _result );
} else if( _result == null ) {
onConnectorFinished();
}
handleEstablishedConnection();
}
/*
* Internal help and test function.
*/
private static void handleEstablishedConnection() {
try {
Log.v( TAG, "Connection is established." );
CookieStore cs = CookieManager.getInstance().getCookieStore();
if( cs != null ) {
Log.v( TAG, "------------cookies------------" );
List<Cookie> list = cs.getCookies();
if( list != null && list.size() > 0 ) {
StringBuilder cookieBuilder = new StringBuilder();
for( Cookie c : list ) {
cookieBuilder
.append( c.getName().trim() )
.append( "=>" )
.append( c.getValue().trim() )
.append( "=>" )
.append( c.getDomain() );
Log.v( TAG, cookieBuilder.toString() );
cookieBuilder.delete( 0, cookieBuilder.length() - 1 );
}
cookieBuilder = null;
} else {
Log.v( TAG, "Empty cookies." );
}
cs = null;
list = null;
}
}
catch( Exception _e ) {
Log.e( TAG, "Error in handleEstablishedConnection: " + _e.getMessage() );
}
finally {
}
}
private HttpURLConnection connect( String _urlStr ) throws Exception {
URL url = null;
HttpURLConnection conn = null;
try {
try {
url = new URL( _urlStr );
}
catch( MalformedURLException e ) {
throw new IllegalArgumentException( "Invalid url: " + _urlStr );
}
conn = preConnect( url );
doConnect( conn );
conn = postConnect( conn );
}
catch( Exception _e ) {
throw _e;
}
finally {
url = null;
}
return conn;
}
private HttpURLConnection preConnect( URL url ) throws Exception {
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches( false );
// http://www.aswinanand.com/2009/01/httpurlconnectionsetfollowredirects-bug/comment-page-1/#comment-13330
// see the url to learn more about the problem of redirect
conn.setInstanceFollowRedirects( false );
conn.setDoOutput( true );// allows body
mBody = getBody();
if( hasBody() ) {
conn.setFixedLengthStreamingMode( mBody.length );
}
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Connection", "Keep-Alive" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded;charset=UTF-8" );
conn.setRequestProperty( "User-Agent", USER_AGENT );
conn.setRequestProperty( "Accept-Encoding", "gzip" );// force server to send in Content-Encoding: gzip .
String cookies = onCookie();
if( !TextUtils.isEmpty( cookies ) ) {
conn.setRequestProperty( "Cookie", onCookie() );
cookies = null;
}
conn.setConnectTimeout( onSetConnectTimeout() );
return conn;
}
/*
* Convenient function to check the exiting of body.
*/
private boolean hasBody() {
return mBody != null && mBody.length > 0;
}
private void doConnect( HttpURLConnection conn ) throws Exception {
OutputStream out; // the outgoing stream
out = conn.getOutputStream();
if( hasBody() ) {
out.write( mBody );
}
out.close();
out = null;
}
private HttpURLConnection postConnect( HttpURLConnection conn ) throws Exception {
int status = conn.getResponseCode();
if( status != HttpURLConnection.HTTP_OK ) {
throw new ConnectorPostConnectException( status );
} else {
CookieManager.getInstance().put( conn.getURL().toURI(), conn.getHeaderFields() );
return conn;
}
}
private byte[] getBody() {
byte[] body = null;
String bodyString = onSetBody();
if( !TextUtils.isEmpty( bodyString ) ) {
body = bodyString.getBytes();
}
return body;
}
// ------------------------------------------------
// Overrides methods here
// ------------------------------------------------
protected int onSetConnectTimeout() {
return DEFAULT_CNN_TIME_OUT;
}
protected String onCookie() {
return null;
}
protected String onSetBody() {
return null;
}
protected void onConnectorConnectTimout() {
Log.e( TAG, "Handling connector timeout gracefully." );
}
protected void onConnectorError( int _status ) {
Log.e( TAG, "Handling connector error(responsed) gracefully: " + _status );
}
protected void onConnectorInvalidConnect( Exception _e ) {
Log.e( TAG, "Handling connector invalid connect(crash) gracefully: " + _e.toString() );
}
/*
* Read data here. The function runs in thread. To hook on UI thread use onConnectorFinished()
*/
protected void onConnectorInputStream( InputStream _in ) {
}
/*
* Last handler for a success connection
*/
protected void onConnectorFinished() {
}
}
Use this util:
mConn = new Util.Connector( getApplicationContext() ) {
#Override
protected String onSetBody() {
String body = null;
try {
StringBuilder bodyBuilder = new StringBuilder();
bodyBuilder
.append( "id=" )//.append(...)
.append( '&' )
.append( "mal=" )//.append(...)
body = bodyBuilder.toString();
bodyBuilder = null;
}
catch( Exception _e ) {
Log.e( TAG, "Error in onCreateBody: " + _e.getMessage() );
}
finally {
}
return body;
}
#Override
protected int onSetConnectTimeout() {
return 10 * 1000;
}
#Override
protected void onConnectorInvalidConnect( Exception _e ) {
super.onConnectorInvalidConnect( _e );
onErr();
}
#Override
protected void onConnectorError( int _status ) {
super.onConnectorError( _status );
onErr();
}
protected void onConnectorConnectTimout() {
super.onConnectorConnectTimout();
onErr();
}
private void onErr() {
//mConn.submit( URL );
};
#Override
protected void onConnectorFinished() {
}
#Override
protected void onConnectorInputStream( InputStream _in ) {
}
};
mConn.submit( URL );

Categories

Resources