Load ProgressBar while executing ASyncTask - android

I'm finishing an app, and now I want to add a progressbar or something like the Material Design Loading circle. I'm gonna use it while the user login.The LoginActivity works basically like this: when the user hits the ok button, an ASyncTask gets some data from my API. What I want is to show a progressBar while the ASyncTask makes the inquiry to my API and recieves back the data. I've try some libraries and some tutorials but didn't get any results.This is my LoginActivity:
package com.tumta.henrique.teste.view;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.tumta.henrique.teste.R;
import com.tumta.henrique.teste.model.ConsultaLogin;
import com.tumta.henrique.teste.util.Connectivity;
import java.util.List;
public class LoginActivity extends ActionBarActivity implements ConsultaLogin.ConsultaConcluidaLoginListener {
EditText txtUsuario, txtSenha;
ActionBar actionbar;
Button btnOk, btnCancelar;
private AlertDialog alerta;
String login, senha;
Connectivity conn = new Connectivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= 21) {
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.azul_nav));
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtUsuario = (EditText) findViewById(R.id.edit_usuario);
txtSenha = (EditText) findViewById(R.id.edit_senha);
txtUsuario.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
txtSenha.requestFocus();
return true;
}
return false;
}
});
txtSenha.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
onClickOk(v);
return true;
}
return false;
}
});
actionbar = getSupportActionBar();
actionbar.hide();
btnOk = (Button) findViewById(R.id.button_ok);
btnCancelar = (Button) findViewById(R.id.button_cancelar);
boolean isConnected = conn.isConnected(this);
if(isConnected == false){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Erro");
builder.setMessage(R.string.aviso_rede);
builder.setPositiveButton(R.string.config, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}
});
builder.setNegativeButton("Sair", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alerta = builder.create();
alerta.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClickOk(View view) {
try {
if (txtUsuario.getText().toString().equals("") || txtSenha.getText().toString().equals("")) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Erro");
builder.setMessage("Preencha todos os campos!");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
login = "";
senha = "";
txtSenha.getText().clear();
txtUsuario.requestFocus();
}
});
alerta = builder.create();
alerta.show();
} else {
login = txtUsuario.getText().toString();
senha = txtSenha.getText().toString();
ConsultaLogin.URL_STRING = "http://186.207.85.205:7001/com.henrique.rest/api/v1/status/login?usu_login="
+ login + "&usu_senha=" + senha;
new ConsultaLogin(this).execute();
}
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Erro");
builder.setMessage("Ocorreu um erro inesperado! \nTente novamente.");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
login = "";
senha = "";
txtUsuario.getText().clear();
txtSenha.getText().clear();
txtUsuario.requestFocus();
}
});
alerta = builder.create();
alerta.show();
}
}
public void onClickCancelar(View view) {
finish();
}
#Override
public void onConsultaConcluida(List<String> result) {
if (result.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Erro");
builder.setMessage("Usuario ou Senha Incorreto!");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
login = "";
senha = "";
txtSenha.getText().clear();
txtUsuario.requestFocus();
}
});
alerta = builder.create();
alerta.show();
} else {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
}
And this is my ASyncTask:
package com.tumta.henrique.teste.model;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Henrique on 16/06/2015.
*/
public class ConsultaLogin extends AsyncTask<Void, Void, List<String>> {
private ConsultaConcluidaLoginListener listener;
//public static String login, senha;
public static String URL_STRING = "";
public ConsultaLogin(ConsultaConcluidaLoginListener listener) {
this.listener = listener;
}
#Override
protected List<String> doInBackground(Void... arg0) {
try {
String resultado = ConsultaServidor();
return InterpretaResultado(resultado);
} catch (IOException e) {
Log.e("Erro", "Ocorreu um erro na consulta ao servidor!", e);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private List<String> InterpretaResultado(String resultado) throws JSONException {
JSONObject object = new JSONObject(resultado);
JSONArray jsonArray = object.getJSONArray("login");
List<String> listaLogin = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonLogin = jsonArray.getJSONObject(i);
if (jsonLogin.has("usu_nome")) {
String nome = jsonLogin.getString("usu_nome");
listaLogin.add(i, nome);
} else listaLogin.clear();
}
return listaLogin;
}
private String ConsultaServidor() throws IOException {
InputStream is = null;
try {
URL url = new URL(URL_STRING);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
conn.getResponseCode();
is = conn.getInputStream();
Reader reader = null;
reader = new InputStreamReader(is);
char[] buffer = new char[2048];
reader.read(buffer);
return new String(buffer);
} finally {
if (is != null) {
is.close();
}
}
}
#Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
}
public interface ConsultaConcluidaLoginListener {
void onConsultaConcluida(List<String> result);
}
}
If you need more details, please ask.

Add the progressbar to your layout (indeterminate), and toggle visibility on when you initialize the async task. On the callback of the async, toggle the visibility off.
On request:
login = txtUsuario.getText().toString();
senha = txtSenha.getText().toString();
yourProgressBar.setVisibility(View.VISIBLE);
ConsultaLogin.URL_STRING = "http://186.207.85.205:7001/com.henrique.rest/api/v1/status/login?usu_login=" + login + "&usu_senha=" + senha;
new ConsultaLogin(this).execute();
On result:
#Override
public void onConsultaConcluida(List<String> result) {
if (result.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Erro");
builder.setMessage("Usuario ou Senha Incorreto!");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
login = "";
senha = "";
txtSenha.getText().clear();
txtUsuario.requestFocus();
}
});
alerta = builder.create();
alerta.show();
} else {
yourProgressBar.setVisibility(View.GONE);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}

Related

ListView displays data twice

I am working on a small application to save the data of the book (such as the name of the book, the type of the book, the author of the book and the year of publication) in a database, but when the data is returned from the databases using CursorLoader It's shown twice in ListView
This is a code of AddBook activity.
package training.android.com.librarycard;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;
public class AddBook extends AppCompatActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int EXISTING_BOOK_LOADER = 0;
Spinner mBookType;
EditText mBookTitle, mBookAuthor, mBookPublishYear;
String bookType;
int position;
private boolean bookHasChanged = false;
private Uri currentBookUri;
private View.OnTouchListener touchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
bookHasChanged = true;
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
Intent intent = getIntent();
if (intent != null) {
currentBookUri = intent.getData();
if (currentBookUri == null) {
setTitle("Add a book");
invalidateOptionsMenu();
} else {
setTitle("Edit a book");
getLoaderManager().initLoader(EXISTING_BOOK_LOADER, null, this);
}
}
mBookType = findViewById(R.id.spinner);
mBookTitle = findViewById(R.id.book_title);
mBookAuthor = findViewById(R.id.book_author);
mBookPublishYear = findViewById(R.id.publish_year);
mBookType.setOnTouchListener(touchListener);
mBookAuthor.setOnTouchListener(touchListener);
mBookTitle.setOnTouchListener(touchListener);
mBookPublishYear.setOnTouchListener(touchListener);
setupBookTypeSpinner();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (currentBookUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_save:
setBook();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!bookHasChanged) {
NavUtils.navigateUpFromSameTask(AddBook.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener
= new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
NavUtils.navigateUpFromSameTask(AddBook.this);
}
};
showUnsavedChangeDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
private void showUnsavedChangeDialog(DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Discard your changes and quit editing?");
builder.setPositiveButton("Discard", discardButtonClickListener);
builder.setNegativeButton("Keep editing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null)
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete this book ?");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteBook();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null)
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteBook() {
if (currentBookUri != null) {
int rowDeleted = getContentResolver().delete(currentBookUri, null, null);
if (rowDeleted == 0)
Toast.makeText(this, "Delete book failed", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Delete book successful", Toast.LENGTH_SHORT).show();
}
finish();
}
public void setupBookTypeSpinner() {
final ArrayAdapter<CharSequence> bookTypeAdapter = ArrayAdapter.createFromResource(
this, R.array.books_type, R.layout.support_simple_spinner_dropdown_item);
bookTypeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mBookType.setAdapter(bookTypeAdapter);
mBookType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
bookType = parent.getSelectedItem().toString();
position = parent.getSelectedItemPosition();
Log.i("BookTypeSelection", bookType+"");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void setBook() {
String bookTitle = mBookTitle.getText().toString().trim();
String bookAuthor = mBookAuthor.getText().toString().trim();
String publishYear = mBookPublishYear.getText().toString().trim();
if (currentBookUri == null && TextUtils.isEmpty(bookTitle) && TextUtils.isEmpty(bookAuthor)
&& TextUtils.isEmpty(publishYear))
return;
Database database = new Database(this);
SQLiteDatabase db = database.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE, bookTitle);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR, bookAuthor);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR, publishYear);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE, bookType);
if (currentBookUri == null) {
Uri uri = getContentResolver().insert(LibraryCardContract.LibraryCard.CONTENT_URI, values);
if (uri == null) {
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
}
} else {
int rowAffected = getContentResolver().update(currentBookUri, values, null, null);
if (rowAffected == 0) {
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
}
}
db.insert(LibraryCardContract.LibraryCard.TABLE_NAME, null, values);
Toast.makeText(this, "Insert new book", Toast.LENGTH_SHORT).show();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String [] projection = {
LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR };
return new CursorLoader(this,currentBookUri,projection,
null,null,null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if(data.moveToFirst()){
String title = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
String type = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
String publishYear = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
String author = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));
mBookTitle.setText(title);
mBookAuthor.setText(author);
mBookType.setSelection(position);
mBookPublishYear.setText(publishYear);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mBookTitle.setText("");
mBookType.setSelection(position);
mBookAuthor.setText("");
mBookPublishYear.setText("");
}
#Override
public void onBackPressed() {
if(!bookHasChanged){
super.onBackPressed();
return;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
};
showUnsavedChangeDialog(discardButtonClickListener);
}
}
And this is a code of Home activity that contains a listView to
display the data.
package training.android.com.librarycard;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.Models.BookCursorAdapter;
import training.android.com.librarycard.Models.BookDetail;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, LoaderManager.LoaderCallbacks<Cursor> {
private static final int BOOK_LOADER = 0;
private ListView mBookList;
private BookCursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mBookList = findViewById(R.id.books_rv);
cursorAdapter = new BookCursorAdapter(this, null);
mBookList.setAdapter(cursorAdapter);
mBookList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Home.this, AddBook.class);
Uri currentPetUri = ContentUris.withAppendedId(LibraryCardContract.LibraryCard.CONTENT_URI, id);
intent.setData(currentPetUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(BOOK_LOADER, null, this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(), AddBook.class);
startActivity(intent);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.delete_all_books:
deleteAllBooks();
return true;
}
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
private void deleteAllBooks() {
int rowDeleted = getContentResolver().delete(LibraryCardContract.LibraryCard.CONTENT_URI,
null, null);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
LibraryCardContract.LibraryCard._ID,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR};
return new CursorLoader(this, LibraryCardContract.LibraryCard.CONTENT_URI,
projection,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
cursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
}
> This is a code of **BookCursorAdapter** class.
package training.android.com.librarycard.Models;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.R;
/**
* Created by Hassan on 4/9/2018.
*/
public class BookCursorAdapter extends CursorAdapter {
public BookCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context)
.inflate(R.layout.book_list,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView bookTitle = view.findViewById(R.id.book_name_tv);
TextView bookAuthor = view.findViewById(R.id.author_tv);
TextView bookType = view.findViewById(R.id.book_type_tv);
TextView publishYear = view.findViewById(R.id.publish_year_tv);
String title = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
String type = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
String year = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
String author = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));
bookAuthor.setText(author);
bookTitle.setText(title);
bookType.setText(type);
publishYear.setText(year);
}
#Override
public int getCount() {
return super.getCount();
}
}
Screenshot of the application
enter image description here

Get single JSON value from response Retrofit

Im trying to get a single value from JSON using Retrofit, i followed a tutorial but i got an error saying that "Class anonymous class derived from Callback must be either declared ...." .
what im specifically trying to achieve is to echo a single json property value in a empty string like String Axe = ""; and i fill it with a specific value from the json file from the server. here is what i tried.
Json format
"axe1": {"test1"}
The ApiInterface
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface {
#GET("test.json")
Call<JsonObject> readJsonFromFileUri();
}
The MainActivity
import android.graphics.Typeface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends ActionBarActivity {
DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
// URL of object to be parsed
// This string will hold the results
String data = "";
class Myads{
String bnr;
String intt;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://yourdomain.com/s/ ")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<JsonObject> jsonCall = apiInterface.readJsonFromFileUri();
jsonCall.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
JsonObject json = new JsonObject(body().toString());
Gson gson = new Gson();
Myads ad = gson.fromJson(jsonString, Myads.class);
Log.i(LOG_TAG, String.valueOf(ad.bnr));
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
Typeface bold = Typeface.createFromAsset(getAssets(),
"fonts/extrabold.otf");
db = new DataBaseHandler(this);
db.openDataBase() ;
TextView cat = (TextView) findViewById(R.id.titlecat);
cat.setTypeface(bold);
TextView alls = (TextView) findViewById(R.id.titlest);
alls.setTypeface(bold);
TextView fav = (TextView) findViewById(R.id.titlefav);
fav.setTypeface(bold);
TextView qday = (TextView) findViewById(R.id.titleqday);
qday.setTypeface(bold);
TextView rate = (TextView) findViewById(R.id.titleqrate);
rate.setTypeface(bold);
btn_quotes = (ImageView) findViewById(R.id.btn_quotes);
//btn_authors= (Button) findViewById(R.id.btn_authors);
btn_categories = (ImageView) findViewById(R.id.btn_categories);
btn_favorites = (ImageView) findViewById(R.id.btn_favorites);
btn_qteday = (ImageView) findViewById(R.id.btn_qteday);
btn_rateus = (ImageView) findViewById(R.id.btn_rateus);
btn_quotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("mode", "allQuotes");
startActivity(intent);
}
});
/*btn_authors.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent author = new Intent(MainActivity.this,
AuteursActivity.class);
startActivity(author);
}
});*/
btn_favorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent favorites = new Intent(MainActivity.this,
QuotesActivity.class);
favorites.putExtra("mode", "isFavorite");
startActivity(favorites);
}
});
btn_categories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent category = new Intent(MainActivity.this,
CategoryActivity.class);
startActivity(category);
}
});
btn_qteday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Intent qteDay = new Intent(MainActivity.this,
QuoteActivity.class);
qteDay.putExtra("id",
preferences.getInt("id", IntialQteOfDayId));
qteDay.putExtra("mode", "qteday");
startActivity(qteDay);
}
});
btn_rateus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage(getResources().getString(
R.string.ratethisapp_msg));
builder.setTitle(getResources().getString(
R.string.ratethisapp_title));
builder.setPositiveButton(
getResources().getString(R.string.rate_it),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Intent fire = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())); //dz.amine.thequotesgarden"));
startActivity(fire);
}
});
builder.setNegativeButton(
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_settings) {
Intent i = new Intent(this, UserSettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
}
return super.onOptionsItemSelected(item);
}
}
So, i want the value of Json axe1 which is test1 to be parsed and put in into the empty string
You are using wrong import:
import com.android.volley.Response;
Replace it with
import retrofit2.Response;
Firstly, your JSON format is invalid, it should be {"axe1": "test1"}.
To store it you could do :
JSONObject json = new JSONObject(response.body().toString());
Log.i(LOG_TAG, json.getString("axe1"));

Using Android back button after delete an item with SwipeDismissListViewTouchListener

I have a problem when using the back-button in my app (API 17). There are two activities in my project:
The main activity with a ListView reading items from a xml-file.
A second activity which is reading the same xml-file but using only the items which has been checked and saved by the main activity.
If I remove an item from the ListView in the second activity and use the app's menu to go back to the main-activity after saving the xml-file when swiping, this item is now unchecked. It's because the xml-file has been altered after swiping and the value for "isDone" was set from true to false.
So far so good!
But if I go back using the Android back-button the deleted item has is still checked.
What went wrong?
I guess it has something to do with the lifecycle of the activities. But I can not figure it out. Do I have to read the altered and saved xml-file in onResume again? I assumed it will be read again when the main-activity starts after using the back-button from the second activity.
And what I really do not understand is this:
When I debug the code I can see that the xml-file was not altered after swipping the item in the second activity and save the changed isDone value to the xml. This seems a little bit strange to me.
Any help would be fine!
Main-Activity:
package com.wbapps.wbshoppinglist;
/**
* Created by Andreas on 9/4/2017.
*/
import android.support.v7.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MainActivity extends AppCompatActivity {
/*wb, 19Sep,2017: not yet
public static final int REQUEST_ID = 1;
*/
ImageButton imgbtnAddItem;
Button btn_create_shopping_list;
EditText input;
//object for the ListView from activity_main.xml
ListView list_view;
List<Task> tasks;
TodoListAdapter adapter;
XmlParser parser;
File file;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
file = new File(Environment.getExternalStorageDirectory(), "tasks.xml");
parser = new XmlParser();
tasks = new ArrayList<Task>();
//file.delete();
if (file.exists()) {
try {
tasks = parser.read(file);
if (tasks.isEmpty()) {
file.delete();
file.createNewFile();
}else {sortList();}
} catch (XmlPullParserException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
//Initialize the variables
imgbtnAddItem = (ImageButton) findViewById(R.id.add_task_button);
btn_create_shopping_list = (Button) findViewById(R.id.create_shopping_list);
/* findViewById(R.id.list_view).requestFocus(); */
input = (EditText) findViewById(R.id.input_task);
/* id list_view identifies the listview from the activity_main.xmll */
list_view = (ListView) findViewById(R.id.list_view);
registerForContextMenu(list_view);
//tasks = new ArrayList<Task>();
adapter = new TodoListAdapter(tasks, this);
list_view.setAdapter(adapter);
//To swipe away an litem from the list
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(
list_view,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
tasks.remove(position);
adapter.notifyDataSetChanged();
}
}
});
list_view.setOnTouchListener(touchListener);
//set the onClickListener for the button
imgbtnAddItem.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (input.getText().length() > 0) {
/* wb, 16Sep2017: look if the new item is already in the list */
Boolean itemfound = false;
for (int i = 0; i<tasks.size(); i++){
if (tasks.get(i).getTaskContent().equalsIgnoreCase(input.getText().toString())){
itemfound = true;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("This item is already in the list!");
AlertDialog dialog = builder.create();
dialog.show();
break;
}
}
if (itemfound == false){
tasks.add(new Task(input.getText().toString(), false));
adapter.notifyDataSetChanged();
sortList();
input.setText("");
}
}
}
});
btn_create_shopping_list.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//startActivity(new Intent(MainActivity.this, ShoppingListActivity.class));
Boolean selected = false;
Task taskTmp;
for (int i = 0; i < tasks.size(); i++) {
taskTmp = tasks.get(i);
if (taskTmp.isDone()) {
selected = true;
break;
}
}
if (selected) {
Intent intent = new Intent(getApplicationContext(), ShoppingListActivity.class);
startActivity(intent);
/* startActivityForResult(intent, REQUEST_ID); */
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("No items for shopping list selected!");
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
#Override
protected void onPause() {
super.onPause();
//wb, Sep 13, 2017:
//before doing something else - like calling a new activity - write the altered list to
//the data sourc file tasks.xml file
try {
parser.write(tasks, file);
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void onResume() {
super.onResume();
/* Do I have to do the same here like in onCreate? It does not work yet!*/
if (file.exists()) {
try {
tasks = parser.read(file);
if (tasks.isEmpty()) {
file.delete();
file.createNewFile();
}else {sortList();}
} catch (XmlPullParserException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_clear_all:
clearDonetasks();
this.adapter.notifyDataSetChanged();
break;
case R.id.action_delete_done_tasks:
deleteDonetasks();
this.adapter.notifyDataSetChanged();
break;
case R.id.action_delete_all:
this.tasks.clear();
this.adapter.notifyDataSetChanged();
break;
}
return super.onOptionsItemSelected(item);
}
//wb, 15 Sep, 2017: take out the hook from checkbox
public void clearDonetasks() {
for (int i = 0; i < tasks.size(); i++) {
if (tasks.get(i).isDone()) {
tasks.get(i).setIsDone(false);
}
}
}
public void deleteDonetasks() {
for (int i = 0; i < tasks.size(); i++) {
if (tasks.get(i).isDone()) {
tasks.remove(i);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = (int) info.id;
switch (item.getItemId()) {
case R.id.context_delete:
this.tasks.remove(position);
this.adapter.notifyDataSetChanged();
return true;
case R.id.context_edit:
createEditDialog(tasks.get(position));
return true;
default:
return super.onContextItemSelected(item);
}
}
public void createEditDialog(final Task task) {
LayoutInflater li = LayoutInflater.from(MainActivity.this);
View dialogView = li.inflate(R.layout.edit_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(dialogView);
final EditText inputText = (EditText) dialogView.findViewById(R.id.edit_dialog_input);
inputText.setText(task.getTaskContent());
final TextView dialogMessage = (TextView) dialogView.findViewById(R.id.edit_dialog_message);
alertDialogBuilder
.setCancelable(true)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
task.setTaskContent(inputText.getText().toString());
sortList();
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
/* wb, 18Sep2017: sort the tasks list */
public void sortList() {
Collections.sort(tasks, new Comparator<Task>() {
#Override
public int compare(Task content1, Task content2) {
/* return o1.getTaskContent().compareTo(o2.getTaskContent()); */
/* ignore case sentsitivity */
return content1.getTaskContent().compareToIgnoreCase(content2.getTaskContent());
}
});
}
}
Second Activity:
package com.wbapps.wbshoppinglist;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by Andreas on 9/4/2017.
*/
public class ShoppingListActivity extends AppCompatActivity {
/*wb, 19Sep2017: Not yet
public static final String RETVAL_KEY = "RETURN STRING";
*/
ListView shopping_list_view;
List<Task> tasks, shoppingTasks;
TodoListAdapter adapter;
XmlParser parser;
File file;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppinglist);
file = new File(Environment.getExternalStorageDirectory(), "tasks.xml");
parser = new XmlParser();
tasks = new ArrayList<Task>();
shoppingTasks = new ArrayList<Task>();
if (file.exists()) {
try {
tasks = parser.read(file);
if (tasks.isEmpty()) {
Toast.makeText(this, "No Items in Shopping List", Toast.LENGTH_SHORT).show();
//file.delete();
//file.createNewFile();
} else {
/*
Collections.sort(tasks, new Comparator<Task>() {
#Override
public int compare(Task o1, Task o2) {
return o1.getTaskContent().compareTo(o2.getTaskContent());
}
});
*/
addDonelistitems();
}
} catch (XmlPullParserException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
file.createNewFile();
} catch (IOException ex) {
Toast.makeText(this, "Task File not existing!", Toast.LENGTH_SHORT).show();
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
//create an instance for the view of the lauout
shopping_list_view = (ListView) findViewById(R.id.shoppingListView);
registerForContextMenu(shopping_list_view);
adapter = new TodoListAdapter(shoppingTasks, this);
shopping_list_view.setAdapter(adapter);
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(
shopping_list_view,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
//wb, 15Sep: With swipe an item uncheck the checkbox for this item in the file for the shopping items
for (int i = 0; i < tasks.size(); i++) {
if (tasks.get(i).getTaskContent() == shoppingTasks.get(position).getTaskContent()) {
tasks.get(i).setIsDone(false);
try {
parser.write(tasks, file);
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
shoppingTasks.remove(position);
adapter.notifyDataSetChanged();
}
}
});
shopping_list_view.setOnTouchListener(touchListener);
}
#Override
public void onBackPressed() {
/* I jaust added a toas there to see if I will reach here */
Toast.makeText(this, "we are in onBackPressed", Toast.LENGTH_SHORT).show();
finish();
}
public void addDonelistitems() {
for (int i = 0; i < tasks.size(); i++) {
if (tasks.get(i).isDone() == true) {
shoppingTasks.add(tasks.get(i));
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = (int) info.id;
switch (item.getItemId()) {
case R.id.context_delete:
this.tasks.remove(position);
this.adapter.notifyDataSetChanged();
return true;
case R.id.context_edit:
createEditDialog(tasks.get(position));
return true;
default:
return super.onContextItemSelected(item);
}
}
public void createEditDialog(final Task task) {
LayoutInflater li = LayoutInflater.from(ShoppingListActivity.this);
View dialogView = li.inflate(R.layout.edit_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ShoppingListActivity.this);
alertDialogBuilder.setView(dialogView);
final EditText inputText = (EditText) dialogView.findViewById(R.id.edit_dialog_input);
inputText.setText(task.getTaskContent());
final TextView dialogMessage = (TextView) dialogView.findViewById(R.id.edit_dialog_message);
alertDialogBuilder
.setCancelable(true)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
task.setTaskContent(inputText.getText().toString());
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
after trying a little bit around today it seems I solved my problem with the back-button. It seems to be I forgot to set the adapter to the list_view in onResume when comming back from the second activity. After changing the code to this
#Override
protected void onResume() {
super.onResume();
/* Do I have to do the same here like in onCreate? It does not work yet!*/
Toast.makeText(this, "onResume is reached!", Toast.LENGTH_SHORT).show();
if (file.exists()) {
try {
tasks = parser.read(file);
if (tasks.isEmpty()) {
file.delete();
file.createNewFile();
}else {
==>>new code here adapter = new TodoListAdapter(tasks, this);
==>>new code here list_view.setAdapter(adapter);
sortList();}
} catch (XmlPullParserException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
everything worked fine.
I guess without the new code the adapter put the values from the old xml-file to the list_view.
Guess I have to learn a lot of more with android!
Many thanks to all who are trying to help me!
Have a nice day wherever you are
Andreas

Native method not found org.opencv.core.mat.n_mat-Android

I followed all steps when dealing with Mat including adding it to AsyncTask when calling but still the same error which is native method not found org.opencv.core.mat.n_mat
Here's the code:
package com.example.myfirstapp;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import com.example.myfirstapp.RegisterMarkerMain.ProcessImage;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Base64;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class CreateApp extends ListActivity {
boolean duplicate = false;
String userID = "";
Intent manage;
String image = "";
Intent refresh;
CandidatesListAdapter adapter;
ProcessImage process;
Mat mRgba;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
Log.i("loading libs", "OpenCV loading status " + status);
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i("loading libs", "OpenCV loaded successfully");
// Load native library after(!) OpenCV initialization
System.loadLibrary("native_sample");
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_app);
manage = new Intent(this, ManageApps.class);
concurrentTasks();
Bundle extras = getIntent().getExtras();
if (extras != null) {
userID = extras.getString("user_id");
Toast.makeText(CreateApp.this, "User id " + userID,
Toast.LENGTH_LONG).show();
}
final Spinner spinner = (Spinner) findViewById(R.id.categories_spinner);
refresh = new Intent(this, ManageApps.class);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.categories_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
// your code here
String category = spinner.getSelectedItem().toString();
Toast.makeText(CreateApp.this,
"Category " + category + " selected",
Toast.LENGTH_SHORT).show();
TextView tv = (TextView) findViewById(R.id.question_title);
tv.setText(category);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
ImageView iv = (ImageView) findViewById(R.id.application_logo);
registerForContextMenu(iv);
iv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
return false;
}
});
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(CreateApp.this, "Long click to add image",
Toast.LENGTH_LONG).show();
}
});
Button submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText et = (EditText) findViewById(R.id.application_name_edit);
if (et.getText().toString().equals(null)
|| et.getText().toString().equals("")) {
Toast.makeText(CreateApp.this,
"App Name can not be empty.", Toast.LENGTH_SHORT)
.show();
} else {
if (spinner.getSelectedItem().toString().equals("Select")
|| spinner.getSelectedItem().toString().equals("")) {
Toast.makeText(CreateApp.this,
"Cateory must be selected.", Toast.LENGTH_SHORT)
.show();
} else {
new AsyncAppDuplicates().execute();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (duplicate == true) {
System.out
.println("Duplicate flag for App Creation inside if "
+ duplicate);
AlertDialog.Builder builder = new AlertDialog.Builder(
CreateApp.this);
builder.setTitle("Warning");
builder.setMessage("An application already exists with this name."
+ "\n" + "Please choose a different name.");
builder.setNegativeButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
// if this button is clicked, just
// close
// the dialog box and do nothing
dialog.cancel();
}
});
builder.show();
} else {
concurrentCreate();
Toast.makeText(CreateApp.this,
"Created Successfully", Toast.LENGTH_SHORT)
.show();
System.out.println("Done");
// EditText app = (EditText)
// findViewById(R.id.application_name_edit);
}
}
}
}
});
}
#SuppressLint("NewApi")
private void concurrentTasks() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new AsyncGetCategories()
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
System.out.println("getting categories");
} else {
new AsyncGetCategories().execute();
}
}
#SuppressLint("NewApi")
private void concurrentCreate() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new AsyncCreateApplication()
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
System.out.println("Creating app");
} else {
new AsyncCreateApplication().execute();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
finish();
manage.putExtra("user_id", userID);
startActivity(manage);
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_app, menu);
return true;
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.contextmenu, menu);
menu.setHeaderTitle("Select an Option");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_take:
Toast.makeText(CreateApp.this, "Opening the Camera",
Toast.LENGTH_SHORT).show();
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, 0);
return true;
case R.id.menu_choose:
Toast.makeText(CreateApp.this, "Opening the Gallery",
Toast.LENGTH_SHORT).show();
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(gallery, "Select Picture"), 1);
return true;
}
return super.onContextItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView iv = new ImageView(this);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
// Uri selectedImage = data.getData();
Toast.makeText(this, "Adding Photo From Camera",
Toast.LENGTH_LONG).show();
iv = (ImageView) findViewById(R.id.application_logo);
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(thumbnail);
Intent r = new Intent(this, RegisterMarkerMain.class);
//startActivity(r);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
image = Base64.encodeToString(b, Base64.DEFAULT);
//r.putExtra("BitmapImage", image);
//startActivityForResult(r, 13);
Toast.makeText(this, "Marker Valid", Toast.LENGTH_LONG).show();
adapter = new CandidatesListAdapter(this);
setListAdapter(adapter);
process = new ProcessImage(this, thumbnail);
process.execute();
//call the main layout from xml
//RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.create_layout_id);
//create a view to inflate the layout_item (the xml with the textView created before)
//View view = getLayoutInflater().inflate(R.layout.layout_item, mainLayout,false);
//add the view to the main layout
// mainLayout.addView(view);
}
break;
case 1:
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Adding Photo From Gallery",
Toast.LENGTH_LONG).show();
Uri targetUri = data.getData();
iv = (ImageView) findViewById(R.id.application_logo);
Bitmap thumbnail = null;
try {
thumbnail = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(targetUri));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iv.setImageBitmap(thumbnail);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG,100, baos);
byte [] b=baos.toByteArray();;
try{
System.gc();
image=Base64.encodeToString(b, Base64.DEFAULT);
}catch(Exception e){
e.printStackTrace();
}catch(OutOfMemoryError e){
baos=new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG,50, baos);
b=baos.toByteArray();
image=Base64.encodeToString(b, Base64.DEFAULT);
Log.e("EWN", "Out of memory error catched");
}
Toast.makeText(this, "Marker Valid", Toast.LENGTH_LONG).show();
}
break;
}
}
public void managePrivacy(View v) {
Intent privacyIntent = new Intent(this, ManagePrivactActivity.class);
startActivity(privacyIntent);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Marker o = (Marker) this.getListAdapter().getItem(position);
Toast.makeText(this, "strength " + o.descriptor.rows(),
Toast.LENGTH_SHORT).show();
// TODO: both Image and descriptor should be sent to server combined
// with location and other info.
// Descriptor of image is n rows * 64 numbers
}
public native void loadCand(long nativeObjAddr, long descriptoradd, int i);
public native int findMarkersNative(long imgAdd);
public class ProcessImage extends AsyncTask<Void, Void, ArrayList<Marker>> {
private Context mContext;
Bitmap bmp;
public ProcessImage(Context context, Bitmap bmp) {
mContext = context;
mRgba = new Mat();
this.bmp = bmp;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
getListView().setVisibility(View.GONE);
//loading.setVisibility(View.VISIBLE);
Utils.bitmapToMat(bmp, mRgba);
}
#Override
protected void onPostExecute(ArrayList<Marker> result) {
getListView().setVisibility(View.VISIBLE);
//loading.setVisibility(View.GONE);
adapter.updateData(result);
// display
Utils.matToBitmap(mRgba, bmp);
//imageView.setImageBitmap(bmp);
super.onPostExecute(result);
}
#Override
protected ArrayList<Marker> doInBackground(Void... params) {
ArrayList<Marker> imagesCand = new ArrayList<Marker>();
// process
int candCount = findMarkersNative(mRgba.getNativeObjAddr());
for (int i = 0; i < candCount; i++) {
Mat cand = new Mat();
Mat descriptor = new Mat();
loadCand(cand.getNativeObjAddr(),
descriptor.getNativeObjAddr(), i);
if (descriptor.rows() > 0) {
Bitmap bmp3 = Bitmap.createBitmap(cand.cols(), cand.rows(),
Bitmap.Config.ARGB_8888);
Utils.matToBitmap(cand, bmp3);
imagesCand.add(new Marker(bmp3, descriptor));
}
}
return imagesCand;
}
}
private class AsyncCreateApplication extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... arg0) {
EditText et = (EditText) findViewById(R.id.application_name_edit);
String s = et.getText().toString();
TextView tv = (TextView) findViewById(R.id.question_title);
String c = tv.getText().toString();
System.out.println("Category yafanan " + c);
ServerAPI.createApplication(s, c, userID, image);
System.out.println("in Background");
return null;
}
protected void onPostExecute(Void result) {
EditText et = (EditText) findViewById(R.id.application_name_edit);
refresh.putExtra("app_name", et.getText().toString());
System.out.println("App created " + et.getText().toString());
refresh.putExtra("user_id", userID);
setResult(RESULT_OK, refresh);
// startActivity(edit);
startActivity(refresh);
}
}
private class AsyncGetCategories extends AsyncTask<Void, Void, Void> {
ArrayList<String> al = null;
ArrayAdapter<String> dataAdapter;
Spinner category = (Spinner) findViewById(R.id.categories_spinner);
#Override
protected Void doInBackground(Void... params) {
System.out.println("do in background");
al = ServerAPI.getCategories();
System.out.println("ArrayList fetched");
return null;
}
#Override
protected void onPostExecute(Void result) {
dataAdapter = new ArrayAdapter<String>(CreateApp.this,
android.R.layout.simple_spinner_item,
new ArrayList<String>());
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
category.setAdapter(dataAdapter);
dataAdapter.add("Select");
for (int i = 0; i < al.size(); i++) {
dataAdapter.add(al.get(i));
// System.out.println(al.remove(i));
}
return;
}
}
private class AsyncAppDuplicates extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... arg0) {
EditText et = (EditText) findViewById(R.id.application_name_edit);
String name = et.getText().toString();
String s = ServerAPI.checkAppDuplicates(name, userID);
System.out.println("Checked and " + s);
if (s.equals("Already there")) {
duplicate = true;
} else {
duplicate = false;
}
return null;
}
}
}
I've googled so much but I can't figure out what's wrong.
Any help would be really appreciated.
I solved it writing the following lines where you declare everything for the activity, before onCreate:
static {
if (!OpenCVLoader.initDebug()) {
// Handle initialization error
}
}
confirm your native_sample.so file has been contained in your libs-->armeabi folder, and usually, the native lib should be loaded in a static code block outside of the activity's life circle methods.

androids listView's setOnItemClickListener works only if do not update data set. after update it stops

I have creating ListView of wifi channels and it works fine, onResume() calls the AsyncTask which updates the list, but after update the click listener stops working, even if I try to set it again. Here is my code:
package co.uk.company.application.ui.wifi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import co.uk.company.application.R;
import co.uk.company.application.injected.ApplicationGlobalState;
import co.uk.company.application.ui.companyActivity;
import co.uk.company.application.ui.dialog.YesNoAlertDialogCreator;
import co.uk.company.sources.telnet.WifiTelnetClass;
import com.google.inject.Inject;
import java.util.ArrayList;
import java.util.Vector;
import roboguice.inject.InjectView;
public class WifiAPsActivity extends companyActivity{
#Inject private ApplicationGlobalState applicationGlobalState;
#InjectView(R.id.wifi_networks_list) private ListView listView1;
private WifiChannels wifiChannels;
private WifiChannel channelSelected;
private ArrayList<WifiChannel> data;
private ArrayList<WifiChannel> dataold;
private Vector <WifiChannel> vect;
private WifiAPsAdapter adapter;
private RealtimeUpdateScreen realtimeUpdateScreen;
private AdapterView.OnItemClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState){
Log.w("","onCreate(...) start");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_networks);
listener= new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
arg0.showContextMenuForChild(arg1);
//if(adapter.getItem(arg2).toString().endsWith(".txt"))
Toast.makeText(getApplicationContext(),getString(R.string.loading), Toast.LENGTH_LONG).show();
}
};
dataold= new ArrayList<WifiChannel>();
data =new ArrayList<WifiChannel>();
wifiChannels=applicationGlobalState.wifiCurrentChannels;
if (wifiChannels != null)
for(WifiChannel chn : wifiChannels.getChannels()){
dataold.add(chn);
data.add(chn);
}
wifiChannels=applicationGlobalState.wifiCurrentChannels5GHz;
if (wifiChannels != null)
for(WifiChannel chn : wifiChannels.getChannels()){
dataold.add(chn);
data.add(chn);
}
adapter = new WifiAPsAdapter(this,R.layout.wifi_networks_item_row, data);
listView1.setAdapter(adapter);
listView1.setItemsCanFocus(false);
registerForContextMenu(listView1);
listView1.setOnItemClickListener(listener);
Log.w("","onCreate(...) finish");
}
#Override
public void onResume(){
Log.w("","onResume() start");
super.onResume();
//realtimeUpdateScreen = new RealtimeUpdateScreen();
//realtimeUpdateScreen.execute(new Object());
Log.w("","onResume() finish");
}
#Override
public void onPause(){
super.onPause();
realtimeUpdateScreen.cancel(true);
realtimeUpdateScreen = null;
Log.w("","onPause() finish");
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
Log.w("","onCreateContextMenu");
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
// menu.setHeaderTitle(fileNames.get(info.position));
channelSelected = data.get(info.position);
menu.add(Menu.NONE, 0, 0, "Connect");
menu.add(Menu.NONE, 1, 1, "Disconnect");
menu.add(Menu.NONE, 2, 2, "Do nothing");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
Log.w("","onContextItemSelected");
int menuItemIndex = item.getItemId();
//final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (menuItemIndex){
case 0:
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.dialog_with_text_fields, null);
alert.setView(promptsView);
final TextView SSIDfield = (TextView) promptsView.findViewById(R.id.ssid_field);
final EditText input2 = (EditText) promptsView.findViewById(R.id.password_field);
SSIDfield.setText(channelSelected.getName());
// final Button okButton = (Button) promptsView.findViewById(R.id.wifi_button_yes);
// final Button cancelButton =(Button)promptsView.findViewById(R.id.wifi_button_no);
// okButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View arg0) {
//
// }
// });
//
// cancelButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View arg0) {
// // alert.
// }
// });
alert.setPositiveButton("OKK",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id) {
String SSID = channelSelected.getName();
String PASSWORD = input2.getText().toString().trim();
if(WifiTelnetClass.getInstance().connect(SSID, PASSWORD))
Toast.makeText(getApplicationContext(), SSID+" Connected", Toast.LENGTH_SHORT).show();
else Toast.makeText(getApplicationContext(), "Not Connected!", Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("CCancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
alert.show();
break;
case 1:
YesNoAlertDialogCreator.create(this, "Are You Sure?",
getString(R.string.sure_delete_result), new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(getApplicationContext(),"Disconnecting!!", Toast.LENGTH_LONG).show();
if(WifiTelnetClass.getInstance().disconnect())
Toast.makeText(getApplicationContext(), " Disconnected", Toast.LENGTH_SHORT).show();
else Toast.makeText(getApplicationContext(), "Not Disconnected!", Toast.LENGTH_SHORT).show();
}
}).show();
Toast.makeText(getApplicationContext(),"Nothing!!!", Toast.LENGTH_LONG).show();
break;
case 2:
YesNoAlertDialogCreator.create(this, "Password please!!!",
getString(R.string.sure_delete_result), new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
Toast.makeText(getApplicationContext(),"It!", Toast.LENGTH_LONG).show();
break;
}
return true;
}
class RealtimeUpdateScreen extends AsyncTask{
#Override
protected void onPreExecute(){
try{
Thread.sleep(50L);
}catch(Exception e){}
}
#Override
protected Object doInBackground(Object... arg0){
while(!isCancelled()){
try{
if(wifiChannels!=applicationGlobalState.wifiCurrentChannels)
publishProgress(arg0);
try{Thread.sleep(50);}catch(Exception e){}
}catch(Exception e){Log.e("","",e);}
}
return null;
}
protected void onProgressUpdate(Object...objects ){
try{
for(WifiChannel chn_ : dataold){
adapter.remove(chn_);
}
}catch(Exception e){Log.e("","",e);}
try{
dataold = new ArrayList<WifiChannel>();
//adapter.notifyDataSetChanged();
vect=applicationGlobalState.wifiCurrentChannels5GHz.getChannels();
for(WifiChannel chn : vect){
dataold.add(chn);
adapter.add(chn);
}
vect=applicationGlobalState.wifiCurrentChannels.getChannels();
for(WifiChannel chn : vect){
dataold.add(chn);
adapter.add(chn);
}
adapter.notifyDataSetChanged();
}catch(Exception e){Log.e("","",e);}
}
}
}
what can it be?
thank You!
Found it: I have to setOnItemClickListener after each notifyDataSetChanged again.

Categories

Resources