Android ListView does not update dynamic location data - android-listview

I have researched this topic thoroughly and found similar questions on StackOverflow but not specific enough for my question. I am trying to update my ListView with a SimpleCursorAdapter. I have a button, "Get Network Location" that when I press it, it dynamically populates my ListView with new location data (id, lat, lon, acc, time) every time the location changes inside method "onLocationChanged". This is done through adding the new location data to the database and setting the cursor to the adapter.
So it works fine until the "Back" button is pressed or the phone changes orientation. In onResume, the listview becomes empty, so I had to open the database again and set the cursor to the adapter and the adapter to listview again. This populates the listview with complete data from database at the time that "onResume" is called.
However, when a new location data gets added in "onLocationChanged", the new data doesn't populate the listview, until "onResume" gets called again. adapter.notifyDataSetChanged is called both in "onResume" an "onLocation" changed but to no avail. My guess is the listview has changed to a different one after "onCreate" is called but I don't know how to resolve that.
Please anyone with knowledge on this issue let me know what is wrong with my code.
Here's my code:
public class MainActivity extends Activity {
LocationManager locMan;
String provider;
Boolean netWork_enabled = false;
private static long MINTIME;
private static float MINDIS;
Cursor cursor;
NetworkScanDB GeoLocInfoDb;
String row;
double lat;
double lon;
double accur;
double time;
EditText etMinTime;
EditText etMinDis;
ListView lv;
SimpleCursorAdapter sd;
String[] columns;
int[] to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize lv
lv = (ListView) findViewById(R.id.listView1);
// getting min time and distance from edit text
etMinTime = (EditText) findViewById(R.id.et_minTime);
etMinDis = (EditText) findViewById(R.id.et_minDis);
// initiating location
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locMan.NETWORK_PROVIDER;
try {
netWork_enabled = locMan.isProviderEnabled(provider);
} catch (Exception ex) {
}
columns = new String[] { NetworkScanDB.Key_RowID,
NetworkScanDB.Key_Lat, NetworkScanDB.Key_Lon,
NetworkScanDB.Key_Accur, NetworkScanDB.Key_Time };
to = new int[] { R.id.t0, R.id.t1, R.id.t2, R.id.t3, R.id.t4 };
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow, cursor,
columns, to, 0); // had to change to api 11., 0=no query
}
LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
try {
GeoLocInfoDb = new NetworkScanDB(MainActivity.this);
GeoLocInfoDb.open();
// insert row into DB
GeoLocInfoDb.insertGeoLocInfo(location.getLatitude(),
location.getLongitude(), location.getAccuracy(),
location.getTime());
cursor = GeoLocInfoDb.getGeoLocInfoCursor();
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow,
cursor, columns, to, 0); // had to change to api 11.,
// 0=no query
Toast.makeText(getApplicationContext(),
"added new location onLocationChanged",
Toast.LENGTH_LONG).show();
// lv = (ListView) findViewById(R.id.listView1);
sd.notifyDataSetChanged();
lv.setAdapter(sd);
GeoLocInfoDb.close();
} catch (Exception e) {
Log.w("nwscan", e.toString());
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
public void getNetworkLocation(View v) {
MINTIME = Long.parseLong(etMinTime.getText().toString());
MINDIS = Float.parseFloat(etMinDis.getText().toString());
if (netWork_enabled) {
locMan.requestLocationUpdates(provider, MINTIME, MINDIS,
locationListenerNetwork);
} else {
Toast.makeText(getApplicationContext(), "network not enable",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(getApplicationContext(), "onResume ", Toast.LENGTH_LONG)
.show();
GeoLocInfoDb = new NetworkScanDB(MainActivity.this);
GeoLocInfoDb.open();
cursor = GeoLocInfoDb.getGeoLocInfoCursor();
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow, cursor,
columns, to, 0); // had to change to api 11., 0=no query
sd.notifyDataSetChanged();
lv.setAdapter(sd);
}
...
}

Related

Pass data from android to flutter

I have added my Android side code:
I know that I need to use a platform channel to pass data,I am unable to figure out:
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends AppCompatActivity {
private Button Btn;
// Intent defaultFlutter=FlutterActivity.createDefaultIntent(activity);
String path;
private Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btn = findViewById(R.id.btn);
isStoragePermissionGranted();
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
path=takeScreenshot();
// activity.startActivity(defaultFlutter);
}
});
//write flutter xode here
//FlutterActivity.createDefaultIntent(this);
}
private String takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
Log.d("path",mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
return mPath;
///openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
return "Error";
}
}
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
}
I will receive a file from the android side, upon receiving I need to display it in a flutter. I also need to use cached engine for transferring data as normally it would cause a delay
You can use the cached engine, this will help me cover up for the delay.
Then you can add a invoke method onpressed that you can send method name and the data you want to pass.
On flutter side,you can create a platform and invoke method through which you can receive requirements and further process it,

in signin the method gettext must be called from ui thread error

I'm trying to create a login for an application. However I have a problem.
This is my code:
in this code there is an error in the getText() in the android studio
actually m creating a login page with the help of the JSONParsing of web API, the login detail sync from the web api
public class Register extends Activity implements OnClickListener{
EditText user, pass, email, mobile;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//si lo trabajan de manera local en xxx.xxx.x.x va su ip local
// private static final String REGISTER_URL = "http://xxx.xxx.x.x:1234/cas/register.php";
//testing on Emulator:
private static final String REGISTER_URL = "http://abc.demo.xxxxxxxxx.xxx/xxx";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
email = (EditText)findViewById(R.id.Email);
mobile = (EditText)findViewById(R.id.etmobile);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
String mobile = mobile.getText().toString();
String email = email.getText().toString();
try {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("mobile", mobile));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
REGISTER_URL, "POST", params);
// full json response
Log.d("Registering attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
You will have to pass EditText values as args in the Async task.
String[] params = {user.getText().toString(),
pass.getText().toString(),
mobile.getText().toString(),
email.getText().toString()};
new CreateUser().execute(params);
You can play with the UI elements only in classes that run in UI thread. Activity or fragments etc.

Issue with UploadServlet in GWT Project - empty MultiPart

I'm developing a web-app using GWT, and I need to upload a file to the server.
I've written this servlet (which I found here on stackoverflow)
public class ImageUploadService extends HttpServlet {
private static final int MAX_FILE_SIZE = 1 * 1024 * 1024;
#Override
protected void doPost(final HttpServletRequest request,
final HttpServletResponse response) {
wlog("INFO: LA SERVLET é PARTITA");
boolean isMultipart = /* ServletFileUpload.isMultipartContent(request); */true;
if (isMultipart) {
wlog("INFO: IL CONTENUTO é MULTIPART");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
try {
List<FileItem> items = upload.parseRequest(request);
wlog("INFO: LISTA PARTI " + Arrays.toString(items.toArray()));
Iterator<FileItem> iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/fileuploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
item.write(uploadedFile);
wlog("INFO: SALVATO FILE SU DISCO");
}
}
wlog("FINE SERVLET");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void wlog(String s) {
System.out.println("UPLOAD SERVLET " + s);
}
}
This servlet is correctly invoked, and the method doPost executes when I perform form.submit() on the client, but the problem is, upload.parseRequest always returns an empty list.
As I seached here on SO the solution, I found that the main cause for this behaviour is that the request has already been parsed before, but, as you can see from the code I posted, I never parse the request before .parseRequest().
I'm really getting mad tryng to understand where the problem stands, as all the solutions suggested so far haven't worked.
Thanks to everyone who will help spot the error..
(If it helps, I may post the client-side code, although I don't think that the issue lies there)
EDIT: inserted client code
private void inserisciSegnalazioneOK() {
final PopupPanel inserisciSegnalazionePopup = new PopupPanel();
VerticalPanel inseriscisegnalazioneholder = new VerticalPanel();
final FormPanel textform = new FormPanel();
final FormPanel uploadform = new FormPanel();
Button inseriscisegnalazionebtn = new Button("INSERISCI SEGNALAZIONE");
VerticalPanel textholder = new VerticalPanel();
VerticalPanel uploadholder = new VerticalPanel();
final Segnalazione segnalazione = new Segnalazione();
final ListBox lbcat = new ListBox();
for (String s : listaCategorie)
lbcat.addItem(s);
final TextBox descrizione = new TextBox();
final GoogleSuggestBox gsb = new GoogleSuggestBox();
final FileUpload fu = new FileUpload();
textholder.add(new Label("scegli la categoria della segnalazione"));
textholder.add(lbcat);
textholder.add(new Label("inserisci una descrizione testuale"));
textholder.add(descrizione);
textholder.add(new Label("inserisci l'indirizzo della segnalazione"));
textholder.add(gsb);
uploadholder.add(new Label(
"se puoi, allega una foto della segnalazione"));
uploadholder.add(fu);
textform.add(textholder);
uploadform.add(uploadholder);
inseriscisegnalazioneholder.add(textform);
inseriscisegnalazioneholder.add(uploadform);
inseriscisegnalazioneholder.add(inseriscisegnalazionebtn);
inserisciSegnalazionePopup.setWidget(inseriscisegnalazioneholder);
inseriscisegnalazionebtn.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub
segnalazione.setCategoria(lbcat.getItemText(lbcat
.getSelectedIndex()));
segnalazione.setDescrizione(descrizione.getText());
segnalazione.setIndirizzo(gsb.getText());
segnalazione.setUtente(username);
log("INFO: upload del file " + fu.getFilename());
textform.submit();
uploadform.submit();
}
});
uploadform.setAction(GWT.getModuleBaseURL() + "imageUpload");
uploadform.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadform.setMethod(FormPanel.METHOD_POST);
uploadform.addSubmitHandler(new FormPanel.SubmitHandler() {
#Override
public void onSubmit(SubmitEvent event) {
// TODO Auto-generated method stub
if (fu.getFilename().length() == 0) {
Window.alert("Non hai eseguito l'upload di nessuna immagine");
event.cancel();
}
}
});
textform.addSubmitHandler(new FormPanel.SubmitHandler() {
#Override
public void onSubmit(SubmitEvent event) {
// TODO Auto-generated method stub
dataLayerService.inserisciSegnalazione(segnalazione,
new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated
// method stub
caught.printStackTrace();
}
#Override
public void onSuccess(Boolean result) {
// TODO Auto-generated
// method stub
if (result) {
Window.alert("Inserimento avvenuto con successo");
inserisciSegnalazionePopup.hide();
gc.getLatLng(segnalazione.getIndirizzo(),
new LatLngCallback() {
#Override
public void onFailure() {
// TODO
// Auto-generated
// method
// stub
}
#Override
public void onSuccess(
LatLng point) {
// TODO
// Auto-generated
// method
// stub
Marker m = new Marker(point);
map.addOverlay(m);
listaMarker.add(m);
}
});
} else
Window.alert("L'inserimento ha avuto esito negativo");
}
});
}
});
inserisciSegnalazionePopup.setAutoHideEnabled(true);
inserisciSegnalazionePopup.setGlassEnabled(true);
inserisciSegnalazionePopup.center();
}
You have to set a name to your FileUpload if you want the field to be sent out to the server.
BTW, why are you using a FormPanel for your "data" form? Why aren't you simply calling the RPC from the submit button's click? or alternatively, why aren't you putting everything in the same uploadForm and processing it all at once (data and uploaded file) on the server in your upload servlet?

Refresh ListView when Device receives GCM IntentService Message

My app is able to receive messages from GCM and saves the messages to the SQLlite database on the phone. The messages are viewable in a activity that has a listview.
In the code below, the onPause() function refreshes the listView. This is not a good implementation because it only works if the activity is not displayed at the time of the update. If the activity is displayed at the time of an update, the list is static and does not update.
Questions:
How to I update the listview when the activity is being displayed? Or is there a way to use a background service to update the adapter, so that whenever the activity is displayed, it always shows the newest data.
is this kind of functionality currently not possible with android and I'll need to implement something else like 'pull-to-refresh'?
refreshing listview in OnResume() crashes the application, and shows a null pointer exception.
Activity:
public class NotesView extends Activity implements OnItemClickListener {
ListView listView;
NoteAdapter objAdapter;
NotificationsDatabase db = new NotificationsDatabase(this);
List<Notes> listAlerts;
String note;
String time;
TextView noteView;
TextView timeView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
// My AsyncTask start...
class MyTask extends AsyncTask<Void, Void, List<Notes>> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NotesView.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
if (isCancelled()) {
this.cancel(true);
}
}
#Override
protected List<Notes> doInBackground(Void... params) {
db.open();
listAlerts = db.getData();
if (isCancelled()) {
this.cancel(true);
}
return null;
}
protected void onPostExecute(List<Notes> alerts) {
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
db.close();
setAdapterToListview();
}
}// end myTask
public void setAdapterToListview() {
objAdapter = new NoteAdapter(NotesView.this, R.layout.row_notes, listAlerts);
objAdapter.sortByNoteDesc();
objAdapter.notifyDataSetChanged();
listView.setAdapter(objAdapter);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Intent intent = new Intent(
NotesView.this.getApplicationContext(),
TabBarExample.class);
intent.putExtra("goToTab", "Alerts");
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onItemClick(AdapterView<?> parent, View viewDel, int position,
long id) {
for (int i = 0; i < 1; i++) {
Notes item = listAlerts.get(position);
int ids = item.getId();
note = item.getNote();
time = item.getTimeStamp();
}
System.out.println(note + " " + time);
//
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
#Override
protected void onDestroy() {
}
}
Code snippets From GCMIntentService
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
//String message = getString(R.string.gcm_message);
System.out.println("onMessage: ");
Bundle extras = intent.getExtras();
String message = extras.getString("message");
String event_id_from_server = extras.getString("server_id");
// displayMessage(context, message);
generateNotification(context, message);
saveMsg(message);
System.out.println("server id is " + event_id_from_server);
if (event_id_from_server != null) {
updateLocalDatabase(event_id_from_server);
}
}
public void saveMsg(String msg) {
boolean worked = true;
try {
NotificationsDatabase entry = new NotificationsDatabase(GCMIntentService.this);
entry.open();
java.util.Date date = new java.util.Date();
Timestamp x = new Timestamp(date.getTime());
String timeStamp = x.toLocaleString();
entry.createEntry(msg, timeStamp);
entry.close();
//update adapter service
} catch (Exception e) {
worked = false;
String error = e.toString();
System.out.println(error);
} finally {
if (worked) {
}
}
}
I cleaned up your code a little bit. Basically all the view assignments should be done once in onCreate, while the loading of the data should be done in onResume(). See if this helps:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
}
#Override
protected void onResume() {
super.onResume();
new MyTask().execute();
}
#Override
protected void onPause() {
super.onPause();
}

How can I get the column number in a SWT table in Eclipse RCP?

My question is How can we find the currently selected column number in the selected row of a SWT Table in Eclipse RCP?
Inside a Listener - e.g. for SWT.Selection - you can use viewer.getCell(...) as illustrated in the following example:
myTableViewer.getTable().addListener(SWT.Selection, new Listener() {
#Override
public void handleEvent(Event event) {
Point p = new Point(event.x, event.y);
ViewerCell cell = myTableViewer.getCell(p);
int columnIndex = cell.getColumnIndex();
//...
}
});
If you want to be sure that the columnindex is updated prior to calling the selectionlistener, then the mousedown event will also work fine:
table.addMouseListener( new MouseAdapter() {
private static final long serialVersionUID = 1L;
#Override
public void mouseDown(MouseEvent event) {
try {
Point p = new Point(event.x, event.y);
ViewerCell cell = viewer.getCell(p);
selectedColumn = cell.getColumnIndex();
} catch (Exception e) {
e.printStackTrace();
}
}
});