Android activity stops working when reading files from /data/data - java

My android application is kind of a text editor. I want to display the list of saved files. But whenever the activity listing the files is called, the activity stops. This code works completely fine when run in emulator but not on the actual device. Debugging the application on phone shows that the app stops when it tries to access the path although no error is displayed in logcat.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class File_List extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.file_list);
Drawable background=getResources().getDrawable(R.drawable.background);
background.setAlpha(100);
final ListView list=(ListView)findViewById(R.id.listView1);
File folder = new File("/data/data/com.example.demo/files"); //for accessing the folder conatining the files
File[] listOfFiles = folder.listFiles(); //for listing the files within the folder
ArrayList<String> liste = new ArrayList<String>();
for(int i=0;i<listOfFiles.length;i++)
{
if(listOfFiles[i].isDirectory()==false)
liste.add(listOfFiles[i].getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, liste);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
// TODO Auto-generated method stub
//Log.e("selected",list.getAdapter().getItem(position).toString());
Common.CommonVar=2;
File file=new File("/data/data/com.example.demo/files/"+list.getAdapter().getItem(position).toString());
String content;
Log.e("file access", file.getName());
try
{
content = new Scanner(file).useDelimiter("\\A").nextLine();
Intent intent=new Intent(File_List.this,MainActivity.class);
intent.putExtra("File_data",content);
startActivity(intent);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}

Change the line as follows
File folder = new File("/data/data/com.example.demo/files");
if(!folder.exists()){
folder.mkdir();
}

Related

Android giving error while accessing json data from the internet

I am a beginner, building a goofy app that uses an online API. I uploaded the .json file to GitHub, from where my app accesses it and gives the output. However, it always runs the statements for onErrorResponse. Am I doing something wrong?
Here's the code for MainActivity:
package com.example.jsonparsing;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DownloadManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
RequestQueue requestQueue;
Button search;
EditText input;
TextView word;
TextView meaning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = findViewById(R.id.button_getMeaning);
input = findViewById(R.id.editText_input);
word = findViewById(R.id.textView_word);
meaning = findViewById(R.id.textView_meaning);
requestQueue = Volley.newRequestQueue(this);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String term = input.getText().toString().toLowerCase();
String displayInput = term.toUpperCase() + ":";
word.setText(displayInput);
JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest(Request.Method.GET, "https://github.com/DeathVenom54/bonerDictionaryDatabase/blob/master/definitions.json", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String definition = response.getString(term);
meaning.setText(definition);
} catch (JSONException e) {
e.printStackTrace();
meaning.setText("Sorry, this word doesn't exist in the boner database.");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Connection error, please check internet connection.", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest1);
}
});
}
}
The project uses Volley and I have added Internet permission in the manifest.
Edit: here's the .json :
https://github.com/DeathVenom54/bonerDictionaryDatabase/blob/master/definitions.json
The json url you have posted is a link to someone's github page with the json, but not the json itself. Whats most likely happening is volley is downloading the HTML page in its entirety which contains the json. Its then complaining that its not correctly formatted json.
If you want that json directly you need to find a way to host it somewhere. For example github has an api that you can access json files like this https://api.github.com/users/mralexgray/repos
For local testing you could always copy it into a local json file and import into the res/raw of your app and reference it from there.

Save markers to csv file

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).

How to get current wallpaper, change it, then restore it later

I'm struggling with why this code won't compile, I'm trying to get the current wallpaper, then change it, then give the option to change it back.
Below is my code, it doesn't compile because it can't resolve symbol 'context' and it says my drawable cannot be converted to an integer which doesn't make any sense whatsoever.
I'm trying to change the drawable to a bitmap AND I have imported the import
android.content.Context
so what is it I am doing wrong here?? this is my code, the onClick stores the wallpaper and starts the change activity, the onPush method resets the wallpaper and exits the app, any help would be appreciated thanks!
import android.content.Context;
import android.app.Activity;
import android.app.WallpaperInfo;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import java.io.IOException;
import static android.app.WallpaperManager.*;
public class SetWallpaperActivity extends Activity {
public Drawable originalWallpaper;
public Bitmap paper1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view) {
WallpaperManager wm = WallpaperManager.getInstance(this);
originalWallpaper = wm.getDrawable();
paper1 = BitmapFactory.decodeResource(context.getResources(),
originalWallpaper);
Intent intent = new Intent(
ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(EXTRA_LIVE_WALLPAPER_COMPONENT,
new ComponentName(this, MyWallpaperService.class));
startActivity(intent);
}
public void onPush(View view) {
WallpaperManager wm = WallpaperManager.getInstance(this);
WallpaperInfo wallpaperInfo = wm.getWallpaperInfo();
if (wallpaperInfo != null) {
try {
wm.setBitmap(paper1);
finish();
} catch (IOException e) {
e.printStackTrace();
}
}
finish();
System.exit(0);
}
}
This is the error code I'm getting:
'decodeResource(android.content.res.Resources, int)' in 'android.graphics.BitmapFactory' cannot be applied to '(android.content.res.Resources, android.graphics.drawable.Drawable)'

Not able to get audio input for simple microphone app

I am in the process of learning out to use libpd with Android and have ran into a problem. I wanted to see if I could get a simple microphone app working. Just an ~adc -> bpfilter -> *2 -> ~dac. I verified that the patched worked with Pure Data and MobMuPlat.
I wrote over the example program "Circle of Fifths" to make sure libpd was included properly. When I modified it using a tutorial to run my own patch, I was unable to get input from the phone's microphone. The following line seemed to be the issue.
PdAudio.initAudio(sampleRate, inpch, 2, 8, true);
If I have the input channels to 0, the app will open but obviously no sound will come out.This is unless I change the patch to just play a tone and set inpch to 0. When the input channels are set inpch to 1,2, or AudioParameters.suggestInputChannels();the application will not open.
I have also tried small sample rates but I had the same issue. Any ideas?
Here is the full main activity:
/**
*
* #author Peter Brinkmann (peter.brinkmann#gmail.com)
*
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*
*/
package org.puredata.android.fifths;
import java.io.File;
import java.io.IOException;
import org.puredata.android.io.AudioParameters;
import org.puredata.android.io.PdAudio;
import org.puredata.android.utils.PdUiDispatcher;
import org.puredata.core.PdBase;
import org.puredata.core.utils.IoUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioGroup;
import android.widget.Toast;
public class CircleOfFifths extends Activity {
private static final String TAG = "GuitarTuner";
private PdUiDispatcher dispatcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initGui();
try {
initPd();
loadPatch();
} catch (IOException e) {
Log.e(TAG, e.toString());
finish();
}
}
private void initGui() {
setContentView(R.layout.main);
}
private void initPd() throws IOException {
// Configure the audio glue
// int sampleRate = AudioParameters.suggestSampleRate();
int sampleRate = 64;
int inpch = AudioParameters.suggestInputChannels();
PdAudio.initAudio(sampleRate, inpch, 2, 8, true);
// Create and install the dispatcher dispatcher = new PdUiDispatcher();
// PdBase.setReceiver(dispatcher);
}
private void loadPatch() throws IOException {
File dir = getFilesDir();
IoUtils.extractZipResource(getResources().openRawResource(R.raw.patch),
dir, true);
File patchFile = new File(dir, "microphone.pd");
PdBase.openPatch(patchFile.getAbsolutePath());
PdAudio.startAudio(this);
}
#Override
protected void onResume() {
super.onResume();
PdAudio.startAudio(this);
}
#Override
protected void onPause() {
super.onPause();
PdAudio.stopAudio();
}
}
You need a permission for recording audio. Try adding
<uses-permission android:name="android.permission.RECORD_AUDIO" />
to your manifest.

Passing date.getTime through activities, using date.setTime in the destination activity, getting NullPointerException

I want to send a certain date.getTime() through activities, and then set it in the destination activity date.setTime(). Here is my code:
Sending activity:
[...]
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Send single item click data to SingleItemView Class
Intent i = new Intent(RecentSightings.this,
AlertViewOnMap.class);
// Pass data "name" followed by the position
i.putExtra("createdAt", alertsList.get(position).getCreatedAt().getTime());
startActivity(i);
}
});
[...]
And this is the receiving activity:
package com.fourbox.bocterapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.parse.ParseGeoPoint;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
public class AlertViewOnMap extends Activity {
public Date alertTime;
DateFormat dateFormat = new SimpleDateFormat("HH:mm");
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(com.fourbox.bocterapp.R.layout.details_design);
alertTime.setTime(getIntent().getLongExtra("createdAt", 0));
[...]
I have checked with the debugger, and the sending activity sends the long variable(miliseconds) right, but when it reaches "alertTime.setTime([...])", i get the following error:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity >>ComponentInfo{com.fourbox.bocterapp/com.fourbox.bocterapp.AlertViewOnMap}: >>java.lang.NullPointerException
I am having problems in realising what I am doing wrong. Could you help me?
With respects.
You forgot to initialize the alertTime variable in the receiving activity.
public Date alertTime = new Date();

Categories