Pull down to refresh in RecyclerView [duplicate] - android

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();
}
});

Related

recycler view showing only one item instead of three

I need some help, I am developing an app with php and android. I'm using the recycler view, but I'm having problems because my list has 3 items and is showing only one, could you help me? I will add my adapter and my main.
AdapterLocalPersonalizado
public class AdapterLocalPersonalizado extends RecyclerView.Adapter<AdapterLocalPersonalizado.MeuViewHolder> {
Context ctx;
List<Local> listaLocal;
connection con = new connection();
public AdapterLocalPersonalizado(List<Local> locais,Context ctx1) {
this.ctx = ctx1;
this.listaLocal = locais;
}
public class MeuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView nome,categoria,endereco,valor;
#SuppressLint("WrongViewCast")
public MeuViewHolder(#NonNull View view) {
super(view);
nome = (TextView) view.findViewById(R.id.namec);
categoria = (TextView) view.findViewById(R.id.categoria);
valor = (TextView) view.findViewById(R.id.valor);
endereco = (TextView) view.findViewById(R.id.ende);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Local objSelecionado = listaLocal.get(position);
if(position != RecyclerView.NO_POSITION){
Intent intent = new Intent(ctx.getApplicationContext(), tela_lista_local.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle bundle = new Bundle();
bundle.putInt("ID",objSelecionado.getId());
ctx.startActivity(intent);
}
}
}
#NonNull
#Override
public MeuViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
Local local = listaLocal.get(i);
Context context = viewGroup.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View linhaView = inflater.inflate(R.layout.activity_tela_lista_local_personalizada, viewGroup, false);
MeuViewHolder viewHolder = new MeuViewHolder(linhaView);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull AdapterLocalPersonalizado.MeuViewHolder meuViewHolder, int i) {
Local local = listaLocal.get(i);
TextView nome = meuViewHolder.nome;
nome.setText(local.getNome());
}
#Override
public int getItemCount() {
return listaLocal.size();
}
}
tela_lista_local (main)
public class tela_lista_local extends AppCompatActivity {
AdapterLocalPersonalizado adapterLocalPersonalizado;
List<Local> localList;
Local local;
String endereco,categoria,token;
connection con = new connection();
ListarLocalAsyncTask listarLocaisAsyncTask;
RecyclerView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tela_lista_local);
token = "tcc";
Intent it = getIntent();
categoria = it.getStringExtra("categoria");
endereco = it.getStringExtra("endereco");
listView = findViewById(R.id.recyclerViewLocal);
listarLocaisAsyncTask = new ListarLocalAsyncTask();
listarLocaisAsyncTask.execute();
}
public class ListarLocalAsyncTask extends AsyncTask<String, String, String> {
String api_token, query;
HttpURLConnection conn;
URL url = null;
Uri.Builder builder;
final String URL_WEB_SERVICES = "http://192.168.0.110/Controller/APIListarLocal.php";
final int READ_TIMEOUT = 10000; // MILISSEGUNDOS
final int CONNECTION_TIMEOUT = 30000;
int response_code;
public ListarLocalAsyncTask( ){
this.builder = new Uri.Builder();
builder.appendQueryParameter("api_categoria", categoria);
}
#Override
protected void onPreExecute() {
Log.i("APIListar", "onPreExecute()");
}
#Override
protected String doInBackground(String... strings) {
Log.i("APIListar", "doInBackground()");
// Gerar o conteúdo para a URL
try {
url = new URL(URL_WEB_SERVICES);
} catch (MalformedURLException e) {
Log.i("APIListar", "MalformedURLException --> " + e.getMessage());
} catch (Exception e) {
Log.i("APIListar", "doInBackground() --> " + e.getMessage());
}
// Gerar uma requisição HTTP - POST - Result será um ArrayJson
// conn
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setRequestProperty("charset", "utf-8");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
} catch (Exception e) {
Log.i("APIListar", "HttpURLConnection --> " + e.getMessage());
}
// Adicionar o TOKEN e/ou outros parâmetros como por exemplo
// um objeto a ser incluido, deletado ou alterado.
// CRUD completo
try {
query = builder.build().getEncodedQuery();
OutputStream stream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(stream, "utf-8"));
writer.write(query);
writer.flush();
writer.close();
stream.close();
conn.connect();
} catch (Exception e) {
Log.i("APIListar", "BufferedWriter --> " + e.getMessage());
}
// receber o response - arrayJson
// http - código do response | 200 | 404 | 503
try {
response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(input)
);
StringBuilder result = new StringBuilder();
String linha = null;
while ((linha = reader.readLine()) != null) {
result.append(linha);
}
return result.toString();
} else {
return "HTTP ERRO: " + response_code;
}
} catch (Exception e) {
Log.i("APIListar", "StringBuilder --> " + e.getMessage());
return "Exception Erro: " + e.getMessage();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
Log.i("APIListar", "onPostExecute()--> Result: " + result);
try {
Local local;
JSONArray jsonArray = new JSONArray(result);
localList = new ArrayList<>();
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
local = new Local(jsonObject.getInt("id"),
jsonObject.getString("nome"),
jsonObject.getString("endereco"),
jsonObject.getString("categoria"),
jsonObject.getString("valor"));
localList.add(local);
Log.i("APIListar", "Estado: -> " + local.getId() + " - " +local.getNome());
}
Toast.makeText(tela_lista_local.this, localList.size() + " local Listados no LogCat", Toast.LENGTH_LONG)
.show();
initial();
}
} catch (Exception e) {
Log.i("APIListar", "onPostExecute()--> " + e.getMessage());
}
}
public void initial(){
adapterLocalPersonalizado = new AdapterLocalPersonalizado(localList, getApplicationContext());
listView.setAdapter(adapterLocalPersonalizado);
listView.setLayoutManager(new LinearLayoutManager(tela_lista_local.this));
}
}
}
It just returns one item but my bank has 3. There are no problems with my API because in debug mode I can see the three items, the problem is when interacting with the list.
Thanks
I guess each item of your recycle view is taking the entire screen and you are only able to see only one item. As #Mike M suggested you can try to scroll and see other item are showing up or not.
If so then make sure your recycle view layout item are not android:layout_width="match_parent" android:layout_height="match_parent".
If you want specific reason, you must post activity_tela_lista_local_personalizada layout.
Happy Coding !

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);
}
}

Disable a Button when Activity Start

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

ListView Scrolling Reset

I'm using an adapter in a list, and the view of the buttons,
Some buttons are blocked, but if you scroll the drop-down list of this button is enabled with another wrong position that does not match, is there any way to solve this?
this is my Adapter
/**
* Created by Isai on 15/03/17.
*/
public class AdapterFood extends ArrayAdapter<Charola.Producto> {
ImageView imgFood;
private String nameService = "AgregarItemCharola";
private String usuarioId = "UsuarioId";
private String productoId = "ProductoId";
private String cantidad = "Cantidad";
private String especificaciones = "Especificaciones";
private String urlComplete = Constantes.URLMAIN + nameService + "?";
private Fragment fragment;
private List<Charola.Producto> productoList;
private int contador;
private String totalCharola;
public AdapterFood(Context context, List<Charola.Producto> productoList, Fragment fragment) {
super(context, 0, productoList);
this.fragment = fragment;
this.productoList = productoList;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View listViewInflate = convertView;
if (convertView == null) {
listViewInflate = inflater.inflate(R.layout.item_menu, viewGroup, false);
}
imgFood = (ImageView) listViewInflate.findViewById(R.id.imageFood);
TextView tituloFood = (TextView) listViewInflate.findViewById(R.id.tittleFood);
TextView descricionFood = (TextView) listViewInflate.findViewById(R.id.descriptionFood);
TextView precio = (TextView) listViewInflate.findViewById(R.id.priceFood);
final Button btnAnadir = (Button) listViewInflate.findViewById(R.id.buttonAnadir);
final Charola.Producto producto = getItem(position);
tituloFood.setText(producto.getNombre().toString());
descricionFood.setText(producto.getDescripcion());
precio.setText("$" + producto.getPrecio() + ".00");
if(producto.isExistencia()){
if (producto.getCantidad() != 0) {
btnAnadir.setText("+ Añadir (" + producto.getCantidad() + ")");
btnAnadir.setBackgroundResource(R.drawable.btns_dialogs);
} else {
btnAnadir.setText("+ Añadir");
btnAnadir.setBackgroundResource(R.drawable.btn_anadir);
}
btnAnadir.setTag(position);
btnAnadir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("La etiqueta cambio del siguiente forma: "+ btnAnadir.getTag());
btnAnadir.setBackgroundResource(R.drawable.btns_dialogs);
new consumeServiceAgregarProductoACharola().execute(urlComplete + "#" + producto.getIdProducto());
System.out.println("+ Añadir("+(producto.getCantidad()+1)+")");
btnAnadir.setText("+ Añadir("+(producto.getCantidad()+1)+")");
producto.setCantidad((producto.getCantidad()+1));
//notifyDataSetChanged();
}
});
}else{
btnAnadir.setBackgroundResource(R.drawable.btn_agotado);
btnAnadir.setBackgroundResource(R.drawable.btn_agotado);
btnAnadir.setText("Agotado");
}
Glide.with(getContext()).
load(producto.getUrlFoto()).placeholder(R.drawable.place_holder)
.into(imgFood);
//Escalar Vistas
/* GuiTools guiTools = GuiTools.getCurrent();
guiTools.scale(tituloFood);
guiTools.scale(descricionFood);
guiTools.scale(precio);
guiTools.scale(btnAnadir);*/
notifyDataSetChanged();
return listViewInflate;
}
//recuperar id usuario
public int recuperarIdUsario() {
SharedPreferences sharedPreferences = getContext().getSharedPreferences("MIS_PREFRENCIAS", Context.MODE_PRIVATE);
int valor = sharedPreferences.getInt("id", 1);
return valor;
}
//Consume service AgregarProducto
class consumeServiceAgregarProductoACharola extends AsyncTask<String, Void, Void> {
private AlertDialogLoading loading;
#Override
protected Void doInBackground(String... params) {
String delimiter = "#";
String[] arrayLink = params[0].split("#");
URL url = null;
try {
url = new URL(arrayLink[0]);
Log.d("URL ---------->", url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");// La conexión es por el metodo POST
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("UsuarioId", recuperarIdUsario());
jsonParam.put("ProductoId", arrayLink[1]);
jsonParam.put("Cantidad", 1);
jsonParam.put("Especificaciones", "");
// Send POST output.
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
StringBuilder sb = new StringBuilder();
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
JSONObject jsonObject = new JSONObject(sb.toString());
Log.d("RESPUESTA ----->",jsonObject.toString());
Log.d("TAMAÑO DEL CH------>", String.valueOf(jsonObject.getInt("TotalCharola")));
totalCharola = String.valueOf(jsonObject.getInt("TotalCharola"));
} else {
Log.e("NO SUCCESS", urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = new AlertDialogLoading(fragment.getActivity());
loading.messageDialog("", "");
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
PrincipalViewController principalViewController = new PrincipalViewController();
principalViewController.ahBottomNavigation.setNotification(totalCharola,2);
loading.closeMessage();
}
}
}

Categories

Resources