[HELP] Adding a Toast message to Decompress activity - Android Q&A, Help & Troubleshooting

Hi everyone,
I am currently working on my first app which grabs a ZIP from the internet and the extracts it to a certain location. Everything works great but I can not figure out how to show a Toast message when the extraction operation is done.
The code I am using for unzipping is:
Code:
package mmarin.test.download;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author jon
*/
public class Decompress{
private String _zipFile;
private String _location;
byte[] buffer = new byte[1024];
int length;
public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
while ((length = zin.read(buffer))>0) {
fout.write(buffer, 0, length);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
I am calling the Decompress activity through a button:
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
}
});
I found this here: http://www.jondev.net/articles/Unzipping_Files_with_Android_(Programmatically) and it works great.
As I said above, only issue is displaying a message that everything is done.
Can someone please help me out?
Thank you!

Please use the Q&A Forum for questions &
Read the Forum Rules Ref Posting
Moving to Q&A

Put the toast after zin.close()

www.stackoverflow.com
Here you can find what you want
Xperian using xda app

http://stackoverflow.com/questions/9824772/toast-after-email-intent-message
Check this
Xperian using xda app

RoberGalarga said:
Put the toast after zin.close()
Click to expand...
Click to collapse
Hey,
I tried this but it doesn't work. I used this statement:
Code:
Toast.makeText(this, "Extraction complete", "LENGTH_SHORT").show();
and I got this error message: The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String).
Help?

The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String)
What the above line means is that you need to pass a Context object, a CharSequence object and an int. You are passing the wrong object types (Decompress, String, String).
The example you saw used the Toast in the activity class itself, that is why the first value passed was a this. The "LENGTH_SHORT" is actually a constant Toast.LENGTH_SHORT.
I am guessing you are making the button object in your main activity class. So i'd suggest making an additional method for the activity class that looks like this
Code:
public void displayToast(CharSequence cs)
{
Toast.makeText(this, cs, Toast.LENGTH_SHORT).show();
}
and then make the following change to your code
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
// Add the following line
displayToast("Unzip complete");
}
});
Let me know if it worked for you.

The_R said:
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String)
What the above line means is that you need to pass a Context object, a CharSequence object and an int. You are passing the wrong object types (Decompress, String, String).
The example you saw used the Toast in the activity class itself, that is why the first value passed was a this. The "LENGTH_SHORT" is actually a constant Toast.LENGTH_SHORT.
I am guessing you are making the button object in your main activity class. So i'd suggest making an additional method for the activity class that looks like this
Code:
public void displayToast(CharSequence cs)
{
Toast.makeText(this, cs, Toast.LENGTH_SHORT).show();
}
and then make the following change to your code
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
// Add the following line
displayToast("Unzip complete");
}
});
Let me know if it worked for you.
Click to expand...
Click to collapse
PERFECT! You're amazing!

Related

[HELP] Filter SimpleAdapter / ListView

Hi, this is actually 2 questions.
I have a list of items stored in one string array and a list of the collections those items are in stored in a second string array.
I want the user to be able to search for an item and see in which collection it exists.
I have managed to do this in a less-than-elegant way by simply combining the 2 string arrays into one and using a ListView with a EditText with a TextWatcher to filter the results. This all works but the result is not so eye-pleasing. I use this to make the distinction between item and collections:
Code:
<item>ITEM \r\n -> COLLECTION(S)
when defining the string array.
As I said, it works but I would like the COLLECTION(S) to be formatted differently from the ITEM. Is this possible in a ListView?
This is my current code:
Code:
public class Search extends Activity {
/** Called when the activity is first created. */
private ListView lv1;
private EditText ed;
private String[] lv_arr;
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
lv1=(ListView)findViewById(R.id.listView1);
ed=(EditText)findViewById(R.id.editText1);
lv_arr = getResources().getStringArray(R.array.all_cont);
lv1.setAdapter(new ArrayAdapter<String>(this, R.layout.row , lv_arr));
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength=ed.getText().length();
arr_sort.clear();
for(int i=0;i<lv_arr.length;i++)
{
if(textlength<=lv_arr[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) lv_arr[i].subSequence(0, textlength)))
{
arr_sort.add(lv_arr[i]);
}}}
lv1.setAdapter(new ArrayAdapter<String>(Search.this, R.layout.row , arr_sort));
}
});
}}
As a second solution that looks more elegant, I used a SimpleAdapter to put the 2 original string arrays in the ListView like this:
Code:
public class Search extends ListActivity {
private String[] l1;
private String[] l2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seach);
ArrayList<Map<String, String>> list = buildData();
String[] from = { "name", "packs" };
int[] to = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, from, to);
setListAdapter(adapter);}
private ArrayList<Map<String, String>> buildData() {
l1 = getResources().getStringArray(R.array.items);
l2 = getResources().getStringArray(R.array.packs);
Integer i;
int to = l1.length;
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
for(i=0;i < to;i++){
list.add(putData(l1[i], l2[i]));
}
return list;
}
private HashMap<String, String> putData(String name, String packs) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("name", name);
item.put("packs", packs);
return item;
}
}
This looks a lot better but I can't figure out how to make use of the EditText to filter the results.
Any help is welcomed!
Hey!
I read your post and I think it would be better to make a class like this:
Code:
public class ListItem
{
public String itemName;
public String collectionName;
}
And then in your Search activity you can Make a single ArrayList of the type ListItem. Populate this array in a way similar to how you are populating the ArrayList of the HashMaps.
Now for setting the ListAdapter you'll have to make a custom view for each row of the list(this custom row could contain two text views, one for the item name and the other for the collection and you can give them their own formatting), and then subclass the ArrayAdapter class and override its getView method.
Heres a couple of links that might be helpful:
http://www.ezzylearning.com/tutoria...droid-listview-items-with-custom-arrayadapter
http://stackoverflow.com/questions/2265661/how-to-use-arrayadaptermyclass
Hope this helps
The_R said:
Hey!
I read your post and I think it would be better to make a class like this:
Code:
public class ListItem
{
public String itemName;
public String collectionName;
}
And then in your Search activity you can Make a single ArrayList of the type ListItem. Populate this array in a way similar to how you are populating the ArrayList of the HashMaps.
Now for setting the ListAdapter you'll have to make a custom view for each row of the list(this custom row could contain two text views, one for the item name and the other for the collection and you can give them their own formatting), and then subclass the ArrayAdapter class and override its getView method.
Heres a couple of links that might be helpful:
http://www.ezzylearning.com/tutoria...droid-listview-items-with-custom-arrayadapter
http://stackoverflow.com/questions/2265661/how-to-use-arrayadaptermyclass
Hope this helps
Click to expand...
Click to collapse
Thanks once more. I looked over the links and I think I have an idea of how to adapt it to my app. Will try it tomorrow and let you know
Yeah. Let me know if it worked.
The_R said:
Yeah. Let me know if it worked.
Click to expand...
Click to collapse
I feel like my head is exploding.
I did what you said but I still have some issues. Here's what I did:
1. Created a new class, Icons:
Code:
public class Icons {
public String icon;
public String title;
public Icons(){
super();
}
public Icons(String icon, String title) {
super();
this.icon = icon;
this.title = title;
}
}
Created a new XML for the style of the ListView:
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/icon_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:textSize="18sp"
android:textColor="#ffffff"
android:textStyle="bold" />
<TextView
android:id="@+id/in_pack"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:textSize="12sp" />
</LinearLayout>
created a new Adapter:
Code:
public class IconsAdapter extends ArrayAdapter<Icons>{
Context context;
int layoutResourceId;
Icons data[] = null;
public IconsAdapter(Context context, int layoutResourceId, Icons[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
IconsHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new IconsHolder();
holder.txtIcon = (TextView)row.findViewById(R.id.icon_name);
holder.txtTitle = (TextView)row.findViewById(R.id.in_pack);
row.setTag(holder);
}
else
{
holder = (IconsHolder)row.getTag();
}
Icons icons = data[position];
holder.txtTitle.setText(icons.title);
holder.txtIcon.setText(icons.icon);
return row;
}
static class IconsHolder
{
TextView txtIcon;
TextView txtTitle;
}
}
Modified my Search class like this:
Code:
public class Search extends Activity {
private ListView listView1;
private String[] l1;
private String[] l2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seach);
l1 = getResources().getStringArray(R.array.items);
l2 = getResources().getStringArray(R.array.packs);
Integer i;
int to = l1.length;
// for(i=0;i < to;i++){}
Icons Icons_data[] = new Icons[]
{
new Icons(l1[0], l2[0]),
new Icons(l1[1], l2[1]),
new Icons(l1[2], l2[2]),
new Icons(l1[3], l2[3]),
};
IconsAdapter adapter = new IconsAdapter(this,
R.layout.row, Icons_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
}
Up until now, everything works (almost) great. Only thing I can't do is figure out how to assign the items in the Icons_data[] array automatically (my for(...) statement doesn't seem to want to fit anywhere). Format looks good and manually inserting data does what it's supposed to. Still need to figure out the automatic data inserting thing...my arrays have 100-150 elements
What I also can't figure out is how the hell to perform the filtering/search on this new special Array... I tried using the old method with the TextWatcher on an EditText field but can't seem to be able to adapt this part:
Code:
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength=ed.getText().length();
[B][U]arr_sort.clear();[/U][/B]
for(int i=0;i<to;i++)
{
if(textlength<=l1[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) l1[i].subSequence(0, textlength)))
{
[B][U]arr_sort.add(l1[i]);[/U][/B]
}
}
}
[B][U]lv1.setAdapter(new ArrayAdapter<String>(Search.this, R.layout.row , arr_sort))[/U][/B];
}
});
ed is the EditText item. I guess I would need to make arr_sort of the type Icons[] and then change the Bold, Underlined lines to something...but no idea what... Is it even possible to do it like i'm doing it? Or should I look for another method to sort it?
Hey I modified your search class:
Code:
public class Search extends Activity {
private ListView listView1;
// Note: I've removed the two String[] class members cause we are going
// store this data in a single Icons[] member
private Icons[] iconsData;
private ArrayList<Icons> arr_sort; // Note: Changed the type of arr_sort
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seach);
// We'll create two local String[] variables to assemble the data
String[] l1 = getResources().getStringArray(R.array.items);
String[] l2 = getResources().getStringArray(R.array.packs);
// get the total number of icons
int totalIcons = l1.length;
// Allocate the data for the Icon[] array
iconsData = new Icons[totalIcons];
// Now to populate the Icon array
for (int i = 0; i < totalIcons; i++)
{
iconsData[i] = new Icons(l1[i], l2[i]);
}
// Rest remains the same
IconsAdapter adapter = new IconsAdapter(this,
R.layout.row, iconsData);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
}
Now you don't need to change the sorting method. Just slight modifications to fit the data structuring is all that is needed.
Code:
public void onTextChanged(CharSequence s, int start, int before, int count)
{
textlength = ed.getText().length();
arr_sort.clear();
for(int i = 0 ; i < to; i++)
{
if(textlength <= iconsData[i].icon.length()) //Note: l1 becomes iconsData[i].icon
{
if(ed.getText().toString().equalsIgnoreCase((String) iconsData[i].icon.subSequence(0, textlength)))
{
arr_sort.add(iconsData[i]); // Note: we'll store iconsData[i] if a match is found
}
}
}
lv1.setAdapter(new IconsAdapter(Search.this, R.layout.row , arr_sort.toArray()));
}
Haven't tested it. So watch out for some possible errors.
I can't thank you enough but I still need your help.
The first part works (modifications to the Search class).
Now, In the same class, after that part, I add the filtering part:
Code:
ed=(EditText)findViewById(R.id.editText1);
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
int textlength = ed.getText().length();
arr_sort.clear();
for(int i=0;i<[B][I]totalIcons[/I][/B];i++)
{
if(textlength <= iconsData[i].icon.length()) //Note: l1 becomes iconsData[i].icon
{
if(ed.getText().toString().equalsIgnoreCase((String) iconsData[i].icon.subSequence(0, textlength)))
{
arr_sort.add(iconsData[i]); // Note: we'll store iconsData[i] if a match is found
}
}
}
listView1.setAdapter(new IconsAdapter(Search.this, R.layout.row , [U][B](Icons[])[/B][/U] arr_sort.toArray()));
}
});
}
}
I had to make 2 changes in order for it not to give any errors. First, I changed the "to" in the for statement to "totalIcons" since that's actually the number we need and "to" was not defined. When I did this I also had to change "totalIcons" to final int since I had this error:"Cannot refer to a non-final variable totalIcons inside an inner class defined in a different method"
Also, I had to add the (Icons[]) at the end because of this error: "The constructor IconsAdapter(Search, int, Object[]) is undefined". The suggested fixes was changing the constructor for IconsAdapter, adding a new constructor or adding the (Icons[]) thing.
Now I have no errors in Eclipse but when I run the app and try to type something in the EditText box the app crashes...I get these errors:
04-12 19:32:27.032: E/AndroidRuntime(998): FATAL EXCEPTION: main
04-12 19:32:27.032: E/AndroidRuntime(998): java.lang.NullPointerException
04-12 19:32:27.032: E/AndroidRuntime(998): at mmarin.iconpack.manager.Search$1.onTextChanged(Search.java:70)
04-12 19:32:27.032: E/AndroidRuntime(998): at android.widget.TextView.sendOnTextChanged(TextView.java:6295)
04-12 19:32:27.032: E/AndroidRuntime(998): at android.widget.TextView.handleTextChanged(TextView.java:6336)
04-12 19:32:27.032: E/AndroidRuntime(998): at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:6485)
04-12 19:32:27.032: E/AndroidRuntime(998): at android.text.SpannableStringBuilder.sendTextChange(SpannableStringBuilder.java:889)
Sorry about the previous untested code. I was in a rush to go somewhere but I saw you online and thought that it'd be better if I replied.
Anyways, I think the problem is that "totalIcons" is a local variable. So remove the final keyword. And in the for loop in the TextWatcher's onTextChanged method instead of using totalIcons use the length property of iconsData:
Code:
for (int i = 0; i < iconsData.length; i++)
Should fix the runtime error
First off, please do all the things you have to do and don't waste your time with me. I really really appreciate you trying to help me so if you don't have time for this, it's absolutely no problem.
Now, the runtime errors are still there after the change
04-12 19:59:24.332: E/AndroidRuntime(1034): FATAL EXCEPTION: main
04-12 19:59:24.332: E/AndroidRuntime(1034): java.lang.NullPointerException
04-12 19:59:24.332: E/AndroidRuntime(1034): at mmarin.iconpack.manager.Search$1.onTextChanged(Search.java:70)
04-12 19:59:24.332: E/AndroidRuntime(1034): at android.widget.TextView.sendOnTextChanged(TextView.java:6295)
04-12 19:59:24.332: E/AndroidRuntime(1034): at android.widget.TextView.handleTextChanged(TextView.java:6336)
04-12 19:59:24.332: E/AndroidRuntime(1034): at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:6485)
04-12 19:59:24.332: E/AndroidRuntime(1034): at mmarin.iconpack.manager.Search$1.onTextChanged(Sea rch.java:70)
Can you paste line 70 of Search.java?
Wait are you doing this in onCreate?
Code:
arr_sort = new ArrayList<Icons>();
That's what I was looking for (actually how to enable line numbers in Eclipse )
here it is:
Code:
arr_sort.clear();
Yep. We aren't creating arr_sort. So its a null pointer.
Do this somewhere in onCreate
Code:
arr_sort = new ArrayList<Icons>();
ok, that solved that issue. now the problem is with this:
Code:
listView1.setAdapter(new IconsAdapter(Search.this, R.layout.row, (Icons[]) arr_sort.toArray()));
What error/exception do you get?
04-12 20:17:26.663: E/AndroidRuntime(1205): FATAL EXCEPTION: main
04-12 20:17:26.663: E/AndroidRuntime(1205): java.lang.ClassCastException: [Ljava.lang.Object;
04-12 20:17:26.663: E/AndroidRuntime(1205): at mmarin.iconpack.manager.Search$1.onTextChanged(Search.java:84)
I guess that the arr_sort.toArray() creates an Object[] but we need a Icons[] resource for the IconsAdapter.
Am I close?
Yea you are right
One quick and ugly solution I can think of is maybe creating an Icons array right after the search and then filling it with all the items in the arraylist. This happens right before you are setting the adapter
Code:
Icons[] data = new Icons[arr_data.size()];
for (int i = 0; i < arr_data.size(); i++)
{
data[i] = arr_data.get(i);
}
listView1.setAdapter(new IconsAdapter(Search.this, R.layout.row, data));
This should work but it isn't really a good solution =/
Quick and ugly works for me! You're 3 for 3!
You get a big special thanks in my App!!!
Once more, thank you and probably I will ask for your help again in a short while, with another issue I can't figure out.
It will probably be about getting a market link for an app through the Share menu in the Play Store and using that information to send an e-mail - but I will try to figure it out for myself . I already found how to get my app in the "Share" menu in the Play Store and also (possibly) how to save that information to a string. Now i have to find out how to actually get my app to start a certain Activity when it is started by the Play Store app. Will do that over the weekend
Sure! I'll be happy to help out with whatever little bit know!

Help skipping line in loading text from the internet.

I am trying to create a simple android app that loads a text file from the internet and displays in a scrollable view. I got the text file to load just fine but I cant seem to figure out how to get it to skip lines using the traditional "/n"
Here is my code:
Code:
package com.brooksytech.ykyacw;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ViewSubmissions extends Activity{
TextView textMsg;
final String textSource = "http://www.fake.com/fake.txt";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewsubmissions);
textMsg = (TextView)findViewById(R.id.textmsg);
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}
}
Supposedly this code is similar to what I want to do but I dont know how to implement it correctly:
Code:
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
All I want it to do is skip a line when it sees /n
Thanks for the help!
brooksyx said:
All I want it to do is skip a line when it sees /n
Thanks for the help!
Click to expand...
Click to collapse
what output are you getting? what does it show. do the "\n"'s show up?
i have this sorta thing in a java app of mine with much the same code.
what are you trying to parse?
Pvy.
Please use the Q&A Forum for questions &
Read the Forum Rules Ref Posting
Thanks ✟
Moving to Q&A

Building app and need help!

Hello everyone,
I have a android app that is a gallery and when they choose the image you can press menu share and it will go to a text box and some quotes where they can select a quote or write their own text and then pick where they want to share to.
My problem is that when i try to share to Facebook or MMS it only shows the text and says "unable to attach. File not supported". But when i choose to share with gmail it has the text and image and everything is fine.
**OK I did some testing the only apps that I know of that are not working are ---> Facebook ( nothing shows up no wording or picture), Google + (only wording), fancy (nothing shows up) , and stock text app (only the text shows up).... if someone could help me that would be great! Thanks**
I have tried to find the solution but cant find it and im not sure where im going wrong.
I was just wondering if someone has any idea how to fix this, and if so can someone tell me how.
Here is the code snippet of what I have:
Code:
public class TextActivity extends Activity {
public static final String SELECTED_IMAGE = "selected_image";
private ListView lv;
private QuotationAdapter qa;
private EditText et;
private Button btShare;
private int selectedImage = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text);
Bundle params = getIntent().getExtras();
if(params != null) {
selectedImage = params.getInt(SELECTED_IMAGE, -1);
}
lv = (ListView) findViewById(R.id.list);
qa = new QuotationAdapter(this);
lv.setAdapter(qa);
et = (EditText) findViewById(R.id.et);
btShare = (Button) findViewById(R.id.btn_share);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
et.setText((String) qa.getItem(pos));
}
});
btShare.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
share(TextActivity.this);
}
});
}
public void share(Activity context) {
if (selectedImage > -1) {
String message = et.getText().toString();
Bitmap resourceImage = BitmapFactory.decodeResource(this.getResources(), selectedImage);
File externalStorageFile = new File(Environment.getExternalStorageDirectory(), "image.jpg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
resourceImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
byte b[] = bytes.toByteArray();
try {
externalStorageFile.createNewFile();
OutputStream filoutputStream = new FileOutputStream(externalStorageFile);
filoutputStream.write(b);
filoutputStream.flush();
filoutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + externalStorageFile.getAbsolutePath()));
context.startActivity(Intent.createChooser(sendIntent,
context.getResources().getString(R.string.text_share_title)));
TextActivity.this.finish();
}
}
public class QuotationAdapter extends BaseAdapter {
public QuotationAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mQuotations.length;
}
public Object getItem(int position) {
return mQuotations[position];
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView i = new TextView(mContext);
i.setPadding(10, 10, 10, 10);
i.setText(mQuotations[position]);
i.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.FILL_PARENT,
ListView.LayoutParams.WRAP_CONTENT));
return i;
}
private Context mContext;
Thanks for look i hope someone knows what im doing wrong :laugh:.
-LivLogik
Hello, change this
Code:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + externalStorageFile.getAbsolutePath()));
context.startActivity(Intent.createChooser(sendIntent,
context.getResources().getString(R.string.text_share_title)));
to this:
Code:
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext=externalStorageFile.getName().substring(externalStorageFile.getName().lastIndexOf(".")+1);
// ext maybe .jpg or .png or ....
String type = mime.getMimeTypeFromExtension(ext);
Intent sendIntent = new Intent("android.intent.action.SEND");
sendIntent.setType(type);
sendIntent.putExtra("android.intent.extra.STREAM",Uri.fromFile(externalStorageFile));
sendIntent.putExtra("android.intent.extra.TEXT",message);
context.startActivity(Intent.createChooser(sendIntent,
context.getResources().getString(R.string.text_share_title)));
livlogik said:
Hello everyone,
I have a android app that is a gallery and when they choose the image you can press menu share and it will go to a text box and some quotes where they can select a quote or write their own text and then pick where they want to share to.
My problem is that when i try to share to Facebook or MMS it only shows the text and says "unable to attach. File not supported". But when i choose to share with gmail it has the text and image and everything is fine.
**OK I did some testing the only apps that I know of that are not working are ---> Facebook ( nothing shows up no wording or picture), Google + (only wording), fancy (nothing shows up) , and stock text app (only the text shows up).... if someone could help me that would be great! Thanks**
I have tried to find the solution but cant find it and im not sure where im going wrong.
I was just wondering if someone has any idea how to fix this, and if so can someone tell me how.
Here is the code snippet of what I have:
Code:
public class TextActivity extends Activity {
public static final String SELECTED_IMAGE = "selected_image";
private ListView lv;
private QuotationAdapter qa;
private EditText et;
private Button btShare;
private int selectedImage = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text);
Bundle params = getIntent().getExtras();
if(params != null) {
selectedImage = params.getInt(SELECTED_IMAGE, -1);
}
lv = (ListView) findViewById(R.id.list);
qa = new QuotationAdapter(this);
lv.setAdapter(qa);
et = (EditText) findViewById(R.id.et);
btShare = (Button) findViewById(R.id.btn_share);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
et.setText((String) qa.getItem(pos));
}
});
btShare.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
share(TextActivity.this);
}
});
}
public void share(Activity context) {
if (selectedImage > -1) {
String message = et.getText().toString();
Bitmap resourceImage = BitmapFactory.decodeResource(this.getResources(), selectedImage);
File externalStorageFile = new File(Environment.getExternalStorageDirectory(), "image.jpg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
resourceImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
byte b[] = bytes.toByteArray();
try {
externalStorageFile.createNewFile();
OutputStream filoutputStream = new FileOutputStream(externalStorageFile);
filoutputStream.write(b);
filoutputStream.flush();
filoutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + externalStorageFile.getAbsolutePath()));
context.startActivity(Intent.createChooser(sendIntent,
context.getResources().getString(R.string.text_share_title)));
TextActivity.this.finish();
}
}
public class QuotationAdapter extends BaseAdapter {
public QuotationAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mQuotations.length;
}
public Object getItem(int position) {
return mQuotations[position];
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView i = new TextView(mContext);
i.setPadding(10, 10, 10, 10);
i.setText(mQuotations[position]);
i.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.FILL_PARENT,
ListView.LayoutParams.WRAP_CONTENT));
return i;
}
private Context mContext;
Thanks for look i hope someone knows what im doing wrong :laugh:.
-LivLogik
Click to expand...
Click to collapse
---------- Post added at 04:56 PM ---------- Previous post was at 04:50 PM ----------
Or use this embed function, it works for me.
Code:
public void ShareContent(String str)
//str is path to save resource image or other file
{
try {
File myFile = new File(str);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext=myFile.getName().substring(myFile.getName().lastIndexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext);
Intent sharingIntent = new Intent("android.intent.action.SEND");
sharingIntent.setType(type);
sharingIntent.putExtra("android.intent.extra.STREAM",Uri.fromFile(myFile));
startActivity(Intent.createChooser(sharingIntent,"Share using"));
}
catch(Exception e){
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
[/COLOR]Or use this embed function, it works for me.
Code:
public void ShareContent(String str)
//str is path to save resource image or other file
{
try {
File myFile = new File(str);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext=myFile.getName().substring(myFile.getName().lastIndexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext);
Intent sharingIntent = new Intent("android.intent.action.SEND");
sharingIntent.setType(type);
sharingIntent.putExtra("android.intent.extra.STREAM",Uri.fromFile(myFile));
startActivity(Intent.createChooser(sharingIntent,"Share using"));
}
catch(Exception e){
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
Click to expand...
Click to collapse
Thanks for your help! Could you tell me where I should put the embed function? Should I replace what you told me to replace with the other code?
Sent from my SGH-T889 using xda premium
First, you save the image as you do.
An then after the catch,
if you call
externalStorageFile.getPath();
you get the path where it has been saved.
You can do something like this:
Code:
String my_saved_image_data=externalStorageFile.getPath();
if(my_saved_image_data!=null)
{
ShareContent(my_saved_image_data);
}
return;
//ShareContent starts the activity.
// Intent sendIntent = new Intent(Intent.ACTION_SEND);
//sendIntent.setType("text/plain");
//sendIntent.putExtra(Intent.EXTRA_TEXT, message);
//sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + externalStorageFile.getAbsolutePath()));
//context.startActivity(Intent.createChooser(sendIntent,
//context.getResources().getString(R.string.text_share_title)));
//TextActivity.this.finish();
livlogik said:
Thanks for your help! Could you tell me where I should put the embed function? Should I replace what you told me to replace with the other code?
Sent from my SGH-T889 using xda premium
Click to expand...
Click to collapse
I think i got it. thanks!
I do have 2 more questions.
1) do you know how to change the background color to black?
2) is there a way to put a cover page when they open the app it has a picture first and then it goes to the actual app? If so could you help me figure it out?
Thanks again for all your help.
elfranchu said:
First, you save the image as you do.
An then after the catch,
if you call
externalStorageFile.getPath();
you get the path where it has been saved.
You can do something like this:
Code:
String my_saved_image_data=externalStorageFile.getPath();
if(my_saved_image_data!=null)
{
ShareContent(my_saved_image_data);
}
return;
//ShareContent starts the activity.
// Intent sendIntent = new Intent(Intent.ACTION_SEND);
//sendIntent.setType("text/plain");
//sendIntent.putExtra(Intent.EXTRA_TEXT, message);
//sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + externalStorageFile.getAbsolutePath()));
//context.startActivity(Intent.createChooser(sendIntent,
//context.getResources().getString(R.string.text_share_title)));
//TextActivity.this.finish();
Click to expand...
Click to collapse
Sent from my SGH-T889 using xda premium
livlogik said:
1) do you know how to change the background color to black?
Click to expand...
Click to collapse
Code:
in yout layout R.layout.activity_text
add attributte to the linear o relative layout
android:background="@android:color/black"
livlogik said:
2) is there a way to put a cover page when they open the app it has a picture first and then it goes to the actual app? If so could you help me figure it out?
Click to expand...
Click to collapse
Yes, create other main activity which only shows the image, and after a time launch this, use a timertask
Code:
//In A activity
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
//here you can start your Activity B.
}
}, 10000);
// change 10000 miliseconds to the miliseconds time you desire
Please, could you pass for my app thread an post your opinion?
http://forum.xda-developers.com/showthread.php?t=2036905
about PhotoDream
OK will do thanks ! If you had time could you maybe explain to me more doing the embed function part? I'm not sure If I'm doing it right.
Sent from my SGH-T889 using xda premium
I´m not sure what you mean by embedding.
Just create an activity, an in its layout an imageview where you display le image.
Set it as launcher in manifest and don´t forget deleting this feature for the other activity.
Launch the activity( where you show the image), wait a time, launch new and finish.
OK thanks that helps me understand that part more. But I was talking about the sharing embed function code that said works for you. Sorry I should have soecified .
elfranchu said:
[/COLOR]Or use this embed function, it works for me.
Code:
public void ShareContent(String str)
//str is path to save resource image or other file
{
try {
File myFile = new File(str);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext=myFile.getName().substring(myFile.getName().lastIndexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext);
Intent sharingIntent = new Intent("android.intent.action.SEND");
sharingIntent.setType(type);
sharingIntent.putExtra("android.intent.extra.STREAM",Uri.fromFile(myFile));
startActivity(Intent.createChooser(sharingIntent,"Share using"));
}
catch(Exception e){
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
Click to expand...
Click to collapse
Sent from my SGH-T889 using xda premium
livlogik said:
OK thanks that helps me understand that part more. But I was talking about the sharing embed function code that said works for you. Sorry I should have soecified .
Sent from my SGH-T889 using xda premium
Click to expand...
Click to collapse
I'm confused
ariadelvana said:
I'm confused
Click to expand...
Click to collapse
The first post he posted said I can add a certain code or use the embeded function that worked for him. I'm just trying to figure out how and where to add the embedded function code because I'm guess I'm doing it wrong
Sent from my SGH-T889 using xda premium
ariadelvana said:
I'm confused
Click to expand...
Click to collapse
Even I was. why he was talking about Embed instead of Activity.
But Relative Layout solution is worked.

[Q] bluetoothchat functions development in Eclipse

Hello,
Recently I started working on bluetooth chat app for my final year project. I took the example coding available in the sample app in Eclipse and trying to improve it. Now I'm trying to insert 2 new functions into it, 1 - the upload button for uploading any files, 2 - bubble chat interface.
I am a beginner at android programming. I tried exploring draw 9 patch for the bubble patch. Somehow I get the bubble chat done, but not perfectly. I can make it send & receive with the same bubble style. What I'm trying to do is, receive message will show in Green bubble while send message will show Yellow Bubble. I tried the getView() method but didn't understand any of it.
As for the upload button, I'm having problem at the uploading part. I get the selecting the file part done, but I don't know how to make it automatically send the file after it being selected. I tried Googling and most of the result show Image upload. Thanks for those image upload tutorial, I get as far as choosing the file. As for uploading it(sending the file to the other paired device), I'm completely clueless...
The part that I'm having problem I highlight it with red color.
Here's my coding(technically it isn't my coding, it the sample coding with minor modification):
package com.example.android.BluetoothChat;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;
/**
* This is the main Activity that displays the current chat session.
*/
@TargetApi(Build.VERSION_CODES.ECLAIR)
public class BluetoothChat extends Activity {
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private TextView mTitle;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private Button mUploadButton;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private BluetoothChatService mChatService = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
@Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
if (mChatService == null) setupChat();
}
}
@Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mConversationView = (ListView) findViewById(R.id.in);
mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
mOutEditText = (EditText) findViewById(R.id.edit_text_out);
mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
mSendButton = (Button) findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
}
});
mUploadButton = (Button) findViewById (R.id.upload_button);
mUploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//when upload button is clicked, choose a file
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"),1);
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
@Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
@Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
@Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
/**
* Sends a message.
* @param message A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
// The action listener for the EditText widget, to listen for the return key
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
if(D) Log.i(TAG, "END onEditorAction");
return true;
}
};
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
mTitle.setText(R.string.title_connected_to);
mTitle.append(mConnectedDeviceName);
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
mTitle.setText(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
mTitle.setText(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent serverIntent = null;
switch (item.getItemId()) {
case R.id.secure_connect_scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
return false;
}
}
accessing bluetoothchat with a single button
i am using bluetooth chat program in my project to send the command from android phone to hc06 bluetooth which is connected to arduino.bluetooth chat program is available in eclipse sample program, now i want to access this program through a single button ,can anybody help me out in this how should i do this , please tell me stepwise first we have to create which activity and then which i am very confused in this
ash124 said:
i am using bluetooth chat program in my project to send the command from android phone to hc06 bluetooth which is connected to arduino.bluetooth chat program is available in eclipse sample program, now i want to access this program through a single button ,can anybody help me out in this how should i do this , please tell me stepwise first we have to create which activity and then which i am very confused in this
Click to expand...
Click to collapse
I'm not sure how to code for arduino. But the part how to access through a button click, i have an idea about that.
you can just open a sample bluetooth chat in eclipse, but instead of set the page auto open. just create a new main page, and add a button then, just "hyperlink" it to the bluetoothchat.
to navigate between pages using a button, i'm sure there's tons of tutorial available in google or you can just search "cornboyz" in youtube. that the best tutorial i followed back when i'm still doing android programming. I can't help you much in coding. but i know where you're getting at. Its been 2 years, last i explore android programming.
so. sorry
kuronatsu said:
I'm not sure how to code for arduino. But the part how to access through a button click, i have an idea about that.
you can just open a sample bluetooth chat in eclipse, but instead of set the page auto open. just create a new main page, and add a button then, just "hyperlink" it to the bluetoothchat.
to navigate between pages using a button, i'm sure there's tons of tutorial available in google or you can just search "cornboyz" in youtube. that the best tutorial i followed back when i'm still doing android programming. I can't help you much in coding. but i know where you're getting at. Its been 2 years, last i explore android programming.
so. sorry
Click to expand...
Click to collapse
thanks kuronatsu for your help

[Q] [Q} Coding a system seting toggle

I am trying to make an app that on launch reads the current on/off(1,0) value of /sys/class/mdnie/mdnie/negative, then changes it to "0 or 1. Someone suggested the below, and I tried it and it does nothing any help is apreciated. Obvously I am a beginner and barely know how to write code but hey gotta start somewhere, this is for a visually impaired friend to toggle negative color mode by assigning a shortcut key to the app. I think it has to do with needing root permision to edit those settings.
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import android.app.Activity;
import android.os.Bundle;
public class ToggleNegativeColorsActivity extends Activity {
private static final String FILEPATH = "/sys/class/mdnie/mdnie/negative";
@Override
public void onCreate(Bundle savedInstanceState) {
try {
String value = readFileAsString(FILEPATH);
if ("1".equals(value.trim())) {
writeStringToFile(FILEPATH, "0");
}
else {
writeStringToFile(FILEPATH, "1");
}}
catch (IOException e) {
e.printStackTrace();
}
finish();
}
// Grabbed from http://stackoverflow.com/questions/1656797/how-to-read-a-file-into-string-in-java
private String readFileAsString(String filePath) throws IOException {
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(
new FileReader(filePath));
char[] buf = new char[1024];
int numRead;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
// Grabbed from http://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java
private void writeStringToFile(String filePath, String value) throws IOException {
PrintWriter out = new PrintWriter(filePath);
out.print(value);
out.close();
}
}

Categories

Resources