Uploading TXT to dropbox - android

I started exploring Android app developing and I'm trying to upload a plain txt file to dropbox to start off. Whenever I've got this working I'll go up a level to pdf etc.
Anyways I keep running stuck in uploading to dropbox.
I've included the libraries, got the activity in my AndroidManifest and tried to follow the official guide as good as I can.
Without further nonsense, this is my code:
AndroidManifest.xml:
<activity
android:name="com.dropbox.client2.android.AuthActivity"
android:launchMode="singleTask"
android:configChanges="orientation|keyboard">
<intent-filter>
<!-- Change this to be db- followed by your app key -->
<data android:scheme="db-mykeyhere" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Layout file where I trigger the onclick to upload on:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".HelloDropboxActivity" >
<Button
android:id="#+id/dropbox_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:text="#string/link_button"/>
<TextView
android:id="#+id/test_output"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
My activity:
public class Settings extends Activity{
final static private String APP_KEY = "myAppKeyIsHere";
final static private String APP_SECRET = "myAppSecretIsHere";
final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
// In the class declaration section:
private DropboxAPI<AndroidAuthSession> mDBApi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// And later in some initialization function:
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
}
public void dropbox_button(View v){
mDBApi.getSession().startAuthentication(Settings.this);
String filePath = getApplicationContext()
.getFilesDir()
.getPath()
.toString() + "/magnus-opus.txt";
File file = new File(filePath);
try {
file.createNewFile();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Entry response = mDBApi.putFile("/magnum-opus.txt", inputStream,
file.length(), null, null);
Log.i("DbExampleLog",
"The uploaded file's rev is: " + response.rev);
} catch (DropboxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void onResume() {
super.onResume();
if (mDBApi.getSession().authenticationSuccessful()) {
try {
// Required to complete auth,
// sets the access token on the session
mDBApi.getSession().finishAuthentication();
AccessTokenPair tokens = mDBApi
.getSession()
.getAccessTokenPair();
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
}
}
And finally my error log:
Could anybody tell me whats wrong here or help me ahead?
For now I just want to be able to upload a .txt file to my dropbox with ANYTHING in it.
Thanks
~Yenthe

You're getting a NoClassDefFound so it sounds like the library isn't properly included. How did you add the library?

Related

Android: Intent is not working onClick

so i am a beginner with programming and basicly just self-teaching everything.
I have managed a few things to work but now I am having the following issue:
Scenario:
I have 2 Activities. In one activity i click a button. onClick it should retreive text in string format from a textfile in the assets folder and send it to the next activity , and show the string in it's textView field.
The problem:
that i now have is: I can click the button, it does open the next activity but i don't see any text.
And i can't really figure out what is going wrong. I tried to set a breakline on the button while debugging it but i cannot make any sence of the info that the debugger is throwing at me. :(
I have the following code:
Activity 1:
IndoorMenuActivity.java
public class IndoorMenuActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_indoor_menu);
Button btn = (Button)findViewById(R.id.button66);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(IndoorMenuActivity.this, ViewActivity.class);
String text = "";
try{
InputStream is = getAssets().open("file.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException ex) {
ex.printStackTrace();
}
intent.putExtra(EXTRA_MESSAGE, text);
startActivity(intent);
}
});
}
}
Activity 2:
ViewActivity.java
public class ViewActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra("com.example.myapp.MESSAGE");
// Capture the layout's TextView and set the string as its text
TextView textView = (TextView) findViewById(R.id.tv_text);
textView.setText(message);
}
}
And my manifest file:
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".GeneralInformationActivity" />
<activity android:name=".IndoorMenuActivity" >
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
<activity android:name=".OutdoorMenuActivity" />
<activity android:name=".ViewActivity" />
<activity android:name=".DatabaseMenuActivity" />
<activity android:name=".ToolsMenuActivity" />
<activity android:name=".SplashActivity"></activity>
</application>
I have no clue on how to solve this or where to even look for the right information, so I can see where I've gone wrong. I just mangled and slashed code together and somehow got most of it working. but with this deeper stuff i'm basically lost.
And to make it a bit more difficult: i don't exactly know any standard programming practices or terms that come with that so some simple explanation and help would be greatly appreciated.
Cheers and thanks in advance.
In ViewActivity.java everything look good, so I say debug your IndoorMenuActivity.java.
Learn to work with Log, this help debug your code:
Place Log.e("MY_TEXT", "text=" + text); after text = new String(buffer);
Then check the Android Monitor and look for the "MY_TEXT", it will be in red.
If you don't see it, that would mean something went wrong while reading the file, now add another Log: Log.e("MY_TEXT", "below is the error"); this time, before the ex.printStackTrace();
To sum up:
try{
InputStream is = getAssets().open("file.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
Log.e("MY_TEXT", "text=" + text);
} catch (IOException ex) {
`Log.e("MY_TEXT", "below is the error");
ex.printStackTrace();
}
I think there might be some issue while you reading the content from InputStream. Please check the exception(in Catch block) in Log and check that again. If any error there please use this code for read data from InputStream
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Welp, just call me stupid. -.-
I found the error...
i misttyped the string of InputStream is = getAssets().open("file.txt")
I edited the text out for this forum but upon reading the code i just noticed i forgot to make the first letter in the stringpath with a capital as i did in the assetfolder.
Anyways verry mucht thanks for the infromation and help.
It works now as it's supposed to do.

Fileoutputstream, where can I store the .data file on emulator, getting FileNotFoundException when trying to create file?

I have the following code and tries to store an array in a .data file. Problem is that I don't know how to do this, I get a filenotfoundException when trying to create a file.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class SimpleBookManager implements BookManager, java.io.Serializable {
private ArrayList<Book> allBooks = new ArrayList<Book>();
public ArrayList<Book> getAllBooks(){
return allBooks;
}
public void saveChanges(){
try{
FileOutputStream f_out = new FileOutputStream("myobject.data");
// Write object with ObjectOutputStream
ObjectOutputStream obj_out = new
ObjectOutputStream (f_out);
// Write object out to disk
obj_out.writeObject(allBooks);
}catch (FileNotFoundException e) {
System.out.println("No file found saveChanges");//Why can't I create a new "myObject.data"?
} catch (IOException e) {
//someCode();
}
}
public void loadBooks(){
try{
// Read from disk using FileInputStream
FileInputStream f_in = new
FileInputStream("myobject.data");
// Read object using ObjectInputStream
ObjectInputStream obj_in =
new ObjectInputStream (f_in);
// Read an object
Object obj = obj_in.readObject();
if (obj instanceof ArrayList<?>)
{
// Cast object to a Vector
allBooks = (ArrayList<Book>) obj;
System.out.println("Worked");
}
}catch (FileNotFoundException e) {
System.out.println("No file found LoadBooks");
} catch (IOException e) {
//someCode();
}
catch (ClassNotFoundException e) {
//someCode();
}
}
public static SimpleBookManager getSimpleBookManager()
{
if (ref == null){
ref = new SimpleBookManager();
}
return ref;
}
public SimpleBookManager(){
}
}
Problem is that it throws filenotfound exeption both when I try to create it and later read it, why? Can't I create .data files on android emulator?
_______________________________________________________
Edit here's my manifest and added the <uses permission> at the end of the file but it still can't create a file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.chalmers.BookApp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="16" />
<application
android:icon="#drawable/ic_launcher"
>
<activity
android:name=".BookApp"
android:label="#string/title_bookapp"
android:uiOptions="splitActionBarWhenNarrow" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AddBookActivity"
android:uiOptions="splitActionBarWhenNarrow" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="edu.chalmers.BookApp" />
</activity>
<activity
android:name=".DetailActivity"
android:uiOptions="splitActionBarWhenNarrow" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="edu.chalmers.BookApp" />
</activity>
<activity
android:name=".EditBookActivity"
android:uiOptions="splitActionBarWhenNarrow" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="edu.chalmers.BookApp" />
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
</manifest>
Change the saveChanges() method to take a Context as a parameter...
public void saveChanges(Context context) {...}
Then in saveChanges(...) try changing this line...
FileOutputStream f_out = new FileOutputStream("myobject.data");
...to...
FileOutputStream f_out = context.openFileOutput("myobject.data", Context.MODE_PRIVATE);
Also pass a Context to loadBooks(...) and change this line...
FileInputStream f_in = new FileInputStream("myobject.data");
...to...
FileInputStream f_in = context.openFileInput("myobject.data");
When calling either method from an Activity you would use this as the context. Example...
myBookManager.saveChanges(this);
myBookManager.loadBooks(this);

Android Socket error in client-server app

When I want to make connection with my server my android application is crashing on the line where a make a new socket.
The code where I make the connection in my ClientAppl.java looks like this.
public class ClientAppl {
private InetAddress host;
private int port;
private Socket link = null;
ObjectInputStream istream;
ObjectOutputStream ostream;
private static MainActivity mainActivity;
private static ClientAppl instance = new ClientAppl(mainActivity);
private ClientAppl(MainActivity frm){
ClientAppl.mainActivity = frm;
}
public static ClientAppl getInstance(){
return instance;
}
public void makeConnection(String sIP, int port) throws IOException, java.net.ConnectException{
if(link == null){
System.out.println("Make connection...");
this.host = InetAddress.getByName(sIP);
this.port = port;
link = new Socket(host, port);
System.out.println("Inputkanaal & outputkanaal vastleggen...");
ostream = new ObjectOutputStream(link.getOutputStream());
System.out.println("OK - output");
istream = new ObjectInputStream(link.getInputStream());
System.out.println("OK - input");
AcceptMessageHandler amh = new AcceptMessageHandler();
Thread t = new Thread(amh);
t.start();
}
}
In MainActivity.java I added this code to start a connection.
txtServerIP = (EditText)findViewById(R.id.txtServerIP);
txtServerPoort = (EditText)findViewById(R.id.txtServerPoort);
try {
ClientAppl.getInstance().makeConnection(txtServerIP.getText().toString(), Integer.parseInt(txtServerPoort.getText().toString()));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (ConnectException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And this is my manifest-file. What's wrong? :(
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="be.howest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET">
</uses-permission>
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name">
<activity
android:name="project.client.pc.view.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
5-14 15:55:28.669: E/AndroidRuntime(572): android.os.NetworkOnMainThreadException
You have always been warned against doing networking operations on the main (UI) thread, and you are now effectively prohibited from doing so by pro-active checks which will cause this fatal exception.
As Chris points out, you'll need to do all of your TCP socket interactions on threads other than the UI thread. In my code, I establish the socket in an AsyncTask, which sounds scary but if I can do it, you certainly can. Here's a decent tutorial:
http://www.vogella.com/articles/AndroidPerformance/article.html
Subsequently, spawn a new thread for each socket "conversation" -- that's not too difficult either.

Permission denial: Can't access the SurfaceFlinger

I get this error when running my app. I also included the permission for surfaceFlinger in manifest.xml
"uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER"
but still it give the same error " can't access the SurfaceFlinger" in LogCat.
Basically i want to run the Development setting code in Dev tools.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
Class partypes[] = new Class[1];
partypes[0] = String.class;
Method getService= ServiceManager.getMethod("getService", partypes );
Object arglist[] = new Object[1];
arglist[0] = "SurfaceFlinger";
IBinder flinger= (IBinder)getService.invoke(smObject, arglist );
// IBinder flinger = ServiceManager.getService("SurfaceFlinger");
if (flinger != null) {
Parcel data = Parcel.obtain();
data.writeInterfaceToken("android.ui.ISurfaceComposer");
data.writeInt(isChecked ? 1 : 0);
flinger.transact(mCode, data, null, 0);
data.recycle();
updateFlingerOptions();
}
} catch (RemoteException ex) {
}
**catch (SecurityException e) {
// TODO Auto-generated catch block
String err=e.toString();
Toast.makeText(DevelopmentSetting.this, err, Toast.LENGTH_SHORT).show();
}**
catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In catch SecurityException it gives the error java.lang.securityException but logcat it says permission denied : can't access surfaceFlinger.
and the manifest.xml is here
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nustian.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER"/>
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".DevelopmentSetting"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Somebody help me.
Your app needs to be signed with the platform certificate to access this permission. Only system apps generally have this. More info here:
https://groups.google.com/forum/#!topic/android-porting/aN6D_vL9xxE
As a workaround, add this to your manifest file. UID media is able to use the surface flinger APIs, so sharing UID with it will allow your app to use it as well.
coreApp="true"
android:sharedUserId="android.uid.media"
Don't forget to add its relative permission:
<uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER" />

NullPointerException Occurs when trying to create a file and write data to it in Android

I am trying to create a file ,if it doesnot exist and tried to write some data to it. The same program I did in java, it was running fine.But when I try to do the same thing in Android I am getting NullPointerException at the place where I am trying to write data to file. And also, I did not find any new file in the current directory .I will share the code here:
xmlpoc.java
public class xmlPoc extends Activity {
String s="<employee>"+
"<details>"+
"<pictag id="+
"\"#drawable/icon\"" +
"mystr"+
"="+
"\"Picture 1\"" +
"myint" +
" =" +
"\"33\"" +
"/>"+
" <name>SandeepKumarSuman</name>"+
"<designation>J2ME Programmer</designation>"+
"<city>Gorakhpur</city>"+
"<state>UP</state>"+
"<name>mohan</name>"+
"<designation>J2ME GAMEProgrammer</designation>"+
"<city>HYD</city>"+
"<state>AP</state>"+
"<name>hari</name>"+
"<designation>Fresher</designation>"+
"<city>GNT</city>"+
"<state>AP</state>"+
"</details>"+
"</employee>";
File f;
FileOutputStream fop;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
f=new File("./myfile1.txt");
try {
fop=new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("New file myfile.txt has been created to the current directory");
}
try {
fop.write(s.getBytes());
fop.flush();
fop.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can anyone help me in sorting out this issue.
Thanks in Advance,
}
Check out the android dev guide here, and if you want to write to the external storage you should add the permissions to your manifest and use "getExternalStorageDirectory()", or "getExternalFilesDir()" if you are using API 8 or higher. You can't just write everywhere, that's why you need to use androids "openFileOutput(" or just write to the external storage.
External storage permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Try f=new File("myfile1.txt");

Categories

Resources