Save markers to csv file - java

I am wondering how to when the user closes the app, save the markers to a file then load them back in when the app is opened again
Here is my code:
package com.example.mapapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends Activity
{
MapView mv;
StringBuffer filePath;
File file;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// This line sets the user agent, a requirement to download OSM maps
Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
setContentView(R.layout.activity_main);
mv = (MapView)findViewById(R.id.map1);
ItemizedIconOverlay<OverlayItem> items;
mv.setBuiltInZoomControls(true);
mv.getController().setZoom(11);
mv.getController().setCenter(new GeoPoint(53.3710,-1.4502));
}
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId() == R.id.addpoi)
{
// react to the menu item being selected...
Intent intent = new Intent(this,AddPoi.class);
startActivityForResult(intent,0);
return true;
}
Intent intent = new Intent(this,AddPoi.class);
startActivityForResult(intent,0);
return false;
}
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menu_mad_assignment, menu);
return true;
}
protected void onActivityResult(int requestCode,int resultCode,Intent intent)
{
if(requestCode==0)
{
if (resultCode==RESULT_OK)
{
Bundle extras=intent.getExtras();
String poiName= extras.getString("poiName");
String poiType= extras.getString("poiType");
String poiDesc= extras.getString("poiDesc");
ItemizedIconOverlay<OverlayItem> items = new ItemizedIconOverlay<>(this, new ArrayList<OverlayItem>(), null);
OverlayItem marker = new OverlayItem(poiName, poiType,poiDesc, new GeoPoint(53.3710,-1.4502));
items.addItem(marker);
mv.getOverlays().add(items);
Log.d("NAME",poiName);
Log.d("NAME",poiType);
Log.d("NAME",poiDesc);
}
}
}
}
Add marker code:
package com.example.mapapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import com.example.luke.madassignment.R;
public class AddPoi extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_poi);
Button addPoiButton = (Button)findViewById(R.id.addPoi);
Button cancelButton = (Button)findViewById(R.id.cancel);
addPoiButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent();
Bundle bundle=new Bundle();
EditText poiName = (EditText)findViewById(R.id.editTextPoiName);
EditText poiType = (EditText)findViewById(R.id.editTextPoiType);
EditText poiDesc = (EditText)findViewById(R.id.editTextPoiDesc);
String poiNameString = poiName.toString();
String poiTypeString = poiName.toString();
String poiDescString = poiName.toString();
bundle.putString("poiName",poiNameString);
bundle.putString("poiType",poiTypeString);
bundle.putString("poiDesc",poiDescString);
intent.putExtras(bundle);
setResult(RESULT_OK,intent);
finish();
}
}
The problem is i cant figure out a way to save the users marker to a file if the app is closed and then load back in the markers when the app is opened again

Use built in sharedPref, simple key value storage, to save data in persistence mode. Check doc here
The SharedPreferences class provides a general framework that allows
you to save and retrieve persistent key-value pairs of primitive data
types. You can use SharedPreferences to save any primitive data:
booleans, floats, ints, longs, and strings. This data will persist
across user sessions (even if your application is killed).
https://developer.android.com/guide/topics/data/data-storage.html#pref

Using OSMBonusPack, you can grab your markers in a KML structure, then save the KML file locally (in onStop).
And load back this KML file when the app is opened (in onCreate).

Related

Trying to add to an arraylist on a different activity each time a button is pressed

So just to practice I've created a Pythagorean theorem calculator app. I want each answer that I obtain to be stored in another activity(a "history" page). I'm trying to use intents to send/receive the arraylist and items. I get the most recent one, but it is overwritten after each press of the button.
package com.example.hypnotenusecalculatorrebuild;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
//ToDo history button is broken. doesn't display listview when pressed.
public void toHistory(View view) {
// Intent intent = new Intent(getApplicationContext(), HistoryActivity.class);
//
// startActivity(intent);
}
public void findHypno(View view) {
Log.i("Info", "button pressed");
EditText editTextNumberA = (EditText) findViewById(R.id.editTextNumberA);
EditText editTextNumberB = (EditText) findViewById(R.id.editTextNumberB);
TextView textViewAnswer = (TextView) findViewById(R.id.textViewAnswer);
String message;
String cSquared;
if (editTextNumberA.getText().toString().isEmpty() || editTextNumberB.getText().toString().isEmpty()) {
message = "Please enter a number for each dimension";
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
} else {
Number numberA = new Number();
Number numberB = new Number();
Number numberC = new Number();
numberA.number = Double.parseDouble(editTextNumberA.getText().toString());
numberB.number = Double.parseDouble(editTextNumberB.getText().toString());
numberA.squareNumber();
numberB.squareNumber();
numberC.number = numberA.number + numberB.number;
numberC.squareRoot();
Log.i("test numberA", String.valueOf(numberA.number));
Log.i("test numberB", String.valueOf(numberB.number));
Log.i("test numberC", String.valueOf(numberC.number));
cSquared = Double.toString(numberC.number);
textViewAnswer.setText(cSquared);
ArrayList<String> historyList = new ArrayList<String>();
historyList.add("test");
Intent intent = new Intent(getApplicationContext(), HistoryActivity.class);
intent.putExtra("answer", cSquared);
intent.putStringArrayListExtra("arrayList", historyList);
startActivity(intent);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
package com.example.hypnotenusecalculatorrebuild;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.function.ToDoubleBiFunction;
public class HistoryActivity extends AppCompatActivity {
public void back(View view) {
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
Intent getList = getIntent();
ArrayList<String> historyList = getList.getStringArrayListExtra("arrayList");
historyList.add(getList.getStringExtra("answer"));
ListView listViewHistory = (ListView) findViewById(R.id.listViewHistory);
ArrayAdapter historyListArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, historyList);
listViewHistory.setAdapter(historyListArrayAdapter);
// ToDo - intent isn't working as attended, only saves one item and gets overwritten each time
//Intent historyIntent = getIntent();
// get extra needs a name from put extra
// String testGetIntent = historyIntent.getStringExtra("answer");
// Log.i("testIntentString", testGetIntent);
// historyList.add(historyIntent.getStringExtra("answer"));
}
}
here is a different approach. make a public interface in a separate file named "extensions" or whatever and initialize your arraylist there like so:
public interface ext {
ArrayList<String> myArray = new ArrayList<String>();
}
this interface is created when the app runs and lives for as long as the app lives meaning you can always access and manipulate it anywhere in your app without worrying whether the activity is being killed or not. so you can add or remove elements to or from it wherever you want.
Access the array this way:
ext.myArray.add("new item")

I m doing barcode scanner. But I can display my resultCode in textview.

I want to display the scan result from ZXING. I integrated ZXING into my android app, the scan works ok. Now I want to display the barcode number result in textview. I'm using zxing library in my project. I set up result.setText(resultCode) but it's not works. so this is code i m'follow from the tutorial.
package com.example.norhanom.barcodeqrcode;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View; //view button or textfield
import android.widget.Toast; //to show and create message for user,appears
as floating view over app
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.google.zxing.Result;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class MainActivity extends AppCompatActivity {
private ZXingScannerView scannerView;
TextView result;
private ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.textView1);
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading");
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
}
public void scanCode(View view){
scannerView = new ZXingScannerView(this); // Programmatically initialize
the scanner view
scannerView.setResultHandler(new ZXingScannerResultHandler());
setContentView(scannerView); //Set the scanner view as the content view
scannerView.startCamera(); //scannerView open camera
}
#Override
public void onPause()
{
super.onPause();
scannerView.stopCamera(); //stop camera on pause
}
class ZXingScannerResultHandler implements ZXingScannerView.ResultHandler
{
#Override
public void handleResult(Result result1)
{
String resultCode = result1.getText(); //get the result
Toast.makeText(MainActivity.this,resultCode,Toast.LENGTH_LONG).show();
//show result
setContentView(R.layout.activity_main);
scannerView.stopCamera(); //camera stop
}
}
}
After using setContentView the next time, you should reassign the views.
//inside handleResult
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.textView1);
result.setText(resultCode);
scannerView.stopCamera();

I can't get my scan results to display in android

When I run my app on a rooted device the ListView is blank and I am not sure why?
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.content.Intent;
import java.util.List;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.widget.Toast;
This is my main class:
public class Network_List extends AppCompatActivity {
WifiManager wifiM;
WifiScanReciever wifiR;
ListView networklist;
String wifis[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network__list);
Search box for searching networks (not yet implemented so don't worry about it)
EditText searchNet = (EditText) findViewById(R.id.networkEditText);
This is the main list to display the network information
networklist = (ListView) findViewById(R.id.networkList);
Search button for the EditText (This is for future development)
Button networkButton = (Button) findViewById(R.id.searchButton);
scanButton is a button that starts the scan
Button scanButton = (Button) findViewById(R.id.buttonScan);
Declares wifiM as wifi manager and gets service
wifiM = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Declares wifiR as WifiScanReciever
wifiR = new WifiScanReciever();
Button for starting the scan
scanButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
wifiM.startScan();
}
});
}
protected void onPause(){
unregisterReceiver(wifiR);
super.onPause();
}
protected void onResume(){
registerReceiver(wifiR, new IntentFilter(wifiM.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
This receives the scan results and puts it an array called wifis. onReceive captures scan results and sets the size of the array wifis.
private class WifiScanReciever extends BroadcastReceiver{
public void onReceive(Context c, Intent intent){
List<ScanResult> wifiSList = wifiM.getScanResults();
wifis = new String[wifiSList.size()];
for (int x = 0; x<wifiSList.size(); x++){
wifis[x] = ((wifiSList.get(x)).toString());
}
networklist.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,wifis));
}
}
}

"Expected resource of type layout/menu" in Android Studio

package com.example.nimehr.streaming;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.example.videostream.VideoViewActivity;
public class MainActivity extends Activity {
Button button;
public MainActivity() {
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(2130903040);
this.button = (Button)this.findViewById(R.id.myButton);
this.button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, VideoViewActivity.class);
MainActivity.this.startActivity(intent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
this.getMenuInflater().inflate(2131165184, menu);
return true;
}
}
I'm getting the error "Expected resource of type layout/menu" at 2130903040 in this.setContentView(2130903040); and 2131165184in this.getMenuInflater().inflate(2131165184, menu); respectively. I fixed it here this.button = (Button)this.findViewById(2131230720); by changing it to R.id.MyButton
DO not do it this way:
this.setContentView(2130903040);
R class exists for a reason to avoid explicitly using ids like this, and to replace it with a more readable cleaner code:
this.setContentView(R.layout.layout_name_here);
From the docs:
When your application is compiled, aapt generates the R class, which contains resource IDs for all the resources in your res/ directory.

Use phone number outside the app?

I don't know if it's possible but in my app I got an activity that show a phone number (retrieve from the web).
Can I send this number to the main phone app of android? For example to call it or save it?
You can create a tel:... Uri, where the ... is replaced by your phone number, then use that Uri with ACTION_DIAL or ACTION_CALL. For example:
package com.commonsware.android.dialer;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class DialerDemo extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
}
public void dial(View v) {
EditText number=(EditText)findViewById(R.id.number);
String toDial="tel:"+number.getText().toString();
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(toDial)));
}
}
The code shown above is from this sample project.

Categories