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.
Related
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?
I created a wallpaper (for my Android 4.0.3) but I have a problem with the preferences.
When I try to invoke a service http-get from PreferenceFragment, I do not get any response. In practice, it seems that call is lost. I tried with a call like:
InputStream stream = null;
StringBuilder fos = null;
try {
URL url = new URL("http://.....");
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new StringBuilder();
int next = -1;
while ((next = reader.read()) != -1) {
fos.append((char)next);
}
} catch (Exception e) {
// ...
} finally {
// ...
}
or with an external framework like libgdx:
HttpRequest httpRequest = new HttpRequest(HttpMethods.GET);
httpRequest.setUrl("http://.....");
NetJavaImpl net = new NetJavaImpl();
net.sendHttpRequest(httpRequest, this);
but nothing happened. On the device no trace about this or a probability exception is present.
I have a manifest like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.mytest.live"
android:installLocation="preferExternal"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-feature
android:name="android.software.live_wallpaper"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MyWallpaperSettings"
android:exported="true"
android:hardwareAccelerated="false"
android:label="MyWallpaperSettings"
android:permission="android.permission.INTERNET" />
<service
android:name=".MyWallpaper"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:permission="android.permission.BIND_WALLPAPER" >
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<meta-data
android:name="android.service.wallpaper"
android:resource="#xml/livewallpaper"
android:value="true" />
</service>
</application>
</manifest>
Do you have any idea? I'm going crazy :(
*edit: Solved, Thanks!! *
private class SendAsyncTask extends AsyncTask<String, String, String>
{
protected String doInBackground(String... status)
{
String result = "";
try
{
String url = "my magic http-get";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
if(response != null && response.getEntity() != null)
{
InputStream stream = response.getEntity().getContent();
try
{
// parse an XML with libgdx ...
XmlReader xmlReader = new XmlReader();
Element root = xmlReader.parse(stream);
Array<Element> childs = root.getChildrenByNameRecursively("mykids");
for (Element child: childs)
{
Element myelement = child.getChildByName("name");
//do something...
}
}
catch (Exception e)
{
//
}
finally
{
try
{
stream.close();
}
catch (Exception e)
{
//
}
}
}
}
catch (Exception e)
{
//
}
return result;
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
}
}
You could possibly get a NetworkOnMainThreadException because you made a network connection in a PreferenceFragment, which runs on main UI thread.
If so, you could move network jobs to a background service. Note that Service runs on main UI thread too. So you need Thread inside the service.
A side note: it seems you swallowed all exceptions with:
try {
// ...
} catch (Exception e) {
// ... => HERE
}
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);
i am new android developer
when ever i run this code i get this error "Source not found." just when it reaches the
url.openStream()
any idea how to fix this?
try {
URL url = new URL("http://pollsdb.com/test.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
<uses-permission
android:name="android.permission.INTERNET" />
add that under your first manifest tag in your AndroidManifest.xml
I have the same problem too. But now, i have been solved this problem by reference http://developer.android.com/guide/components/processes-and-threads.html
about the thread use.
You need to create a worker thread to work for open the URL stream rather than using the main thread(UI thread).
Of course, you also need to add
<uses-permission android:name="android.permission.INTERNET" />
in your AndroidManifest.xml
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.