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.
Related
Well... I am trying to create an application using the TTS Engine.
I can already make it, work, no problem. However I need my buttons to be dinamic, they will come from a database.
**So far you guys have helped me a lot, since now I can do it thanks to the tips I got from you guys.**
**Well.. now I am stuck again.**
Every new button that I create I attach an OnClickListener so it can start the TTS and speak something.
However it's an inner method, so, when I try to run the code below, it gives me a NullPointerException when it tries to "speak" using the TTS. I know the TTS object is out of context, so, **How can I solve this?**
Below the code. It's a little big since I wanted to include everything:
PLEASE JUMP TO THE "HERE IS MY PROBLEM!!!" comment so you guys can see exactly where my problem is. I know where it is, but I don't know how to solve it =(
Any help is appreciatted! =)
Code:
public class LivoxTesteActivity extends Activity implements OnInitListener{
/** Called when the activity is first created. */
private int MY_DATA_CHECK_CODE = 0;
public TextToSpeech tts;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
LinearLayout lgeral = new LinearLayout (this);
lgeral.setOrientation(LinearLayout.VERTICAL);
lgeral.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f));
String array[][] = {{"Comer","eat", "Eu quero comer", "1"},
{"Abraço","hug", "Eu quero um abraço", "2"},
{"Assustado","afraid", "Eu estou com medo", "3"},
{"Beber","drink", "Eu quero beber", "4"}};
int x = array.length;
int qtdeLinhas = 2;
for (int j = 0; j < qtdeLinhas; j++) {
LinearLayout l1 = new LinearLayout (this);
l1.setOrientation(LinearLayout.HORIZONTAL);
l1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f));
FrameLayout fl;
for (int i = 0; i < array.length; i++) {
fl = (FrameLayout)LayoutInflater.from(getBaseContext()).inflate(R.layout.framelayoutstyle, l1, false);
TextView textoEscrito;
textoEscrito = (TextView)LayoutInflater.from(getBaseContext()).inflate(R.layout.textviewstyle, fl, false);
textoEscrito.setText(array[i][0]);
final String texto = textoEscrito.getText().toString();
final String textoFalar = array[i][2];
ImageButton btn;
btn = (ImageButton)LayoutInflater.from(getBaseContext()).inflate(R.layout.imagebuttonstyle, fl, false);
btn.setImageResource(this.getResources().getIdentifier("drawable/" + array[i][1], null, this.getPackageName()));
btn.setOnClickListener(new Button.OnClickListener(){
public void onClick (View v){
Toast.makeText(getBaseContext(), texto, Toast.LENGTH_SHORT).show();
//*******************************
//HERE IS MY PROBLEM!!!
//*******************************
tts.speak(txtFl, TextToSpeech.QUEUE_ADD, null);
//*******************************
//WHEN I TRY TO RUN THE ABOVE IT GIVES A NULLPOINTEREXCEPTION!!!
//*******************************
}
});
fl.addView(btn);
fl.addView(textoEscrito);
l1.addView(fl);
}
lgeral.addView(l1);
}
setContentView(lgeral);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
}
else if (status == TextToSpeech.ERROR) {
}
}
@Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
By the way... the method Toast.makeText(getBaseContext(), texto, Toast.LENGTH_SHORT).show(); works fine. I believe that's because the Toast is a static class.
So, maybe the solution is to create a static class with the method to speak? Ideas? How can I do it?
Questions or Problems Should Not Be Posted in the Development Forum
Please Post in the Correct Forums
Moving to Q&A
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!
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
Hello guys first of all I'm new here so i hope i make everything correct and I'm in the right section.
I just searched for the Stock S3 Gallery (the same like Note 2 with Gallery Flow Effect) but I couldn't find somehting that runs on AOSP Roms, so I just googled a little bit and found these Code (Source was stackoverflow.com, sorry but I can't post the links because Forum Rules with 10 Posts).
Code:
gal_caterories.setAdapter(new CategoryPreferenceAdapter (context,
response.customOfferPojo.offerAvailableCategories,1));
public class CategoryPreferenceAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
public static List<String> thumbnailsselection;
private ViewHolder holder = new ViewHolder();
private List<CategoriesClass> categories = new ArrayList<CategoriesClass>();
public static final int ACTIVITY_CREATE = 10;
public static List<Integer> prefferedCategories = new ArrayList<Integer>();
private int i = 0;
// Keep all Images in array
// public Integer[] mThumbIds = { R.drawable.pic_1, R.drawable.pic_2,
// R.drawable.pic_3, R.drawable.pic_4, R.drawable.pic_5,
// R.drawable.pic_6, R.drawable.pic_7, R.drawable.pic_8,
// R.drawable.pic_9, R.drawable.pic_10, R.drawable.pic_11,
// R.drawable.pic_12, R.drawable.pic_13, R.drawable.pic_14,
// R.drawable.pic_15 };
public CategoryPreferenceAdapter(Context c,
List<CategoriesClass> categories, List<Integer> prefferedCategories) {
this.mContext = c;
this.categories = categories;
this.prefferedCategories = prefferedCategories;
mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
thumbnailsselection = new ArrayList<String>();
}
class ViewHolder {
ImageView imageview;
TextView tv_categoryname;
// LinearLayout ll_category_selection;
CheckBox cb_check_category;
}
[user=439709]@override[/user]
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = mInflater
.inflate(R.layout.template_categories_grid, null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.iv_image_category);
holder.tv_categoryname = (TextView) convertView
.findViewById(R.id.tv_categoryname);
// holder.ll_category_selection = (LinearLayout) convertView
// .findViewById(R.id.ll_category_selection);
holder.cb_check_category = (CheckBox) convertView
.findViewById(R.id.cb_check_category);
if (prefferedCategories.contains(categories.get(position).categoryid)) {
holder.cb_check_category.setChecked(true);
} else {
holder.cb_check_category.setChecked(false);
holder.cb_check_category.setBackgroundColor(Color.TRANSPARENT);
}
holder.tv_categoryname.setText(categories.get(position).category
.toUpperCase());
holder.cb_check_category
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
prefferedCategories.add(categories.get(position).categoryid);
} else {
holder.cb_check_category
.setBackgroundColor(Color.TRANSPARENT);
prefferedCategories.remove(categories.get(position).categoryid);
}
}
});
ImageLoader imageload = new ImageLoader(mContext);
imageload.DisplayImage(
categories.get(position).defaultCategoryImage.toString(),
holder.imageview);
holder.imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
return convertView;
}
[user=439709]@override[/user]
public int getCount() {
// TODO Auto-generated method stub
return categories.size();
}
[user=439709]@override[/user]
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
[user=439709]@override[/user]
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}
Can someone maybe build an App with this Code? I ask because I have no clue about that, but I think the sourcecode is good and many guys would be happy. Maybe some Guy has the time to do it? (It is maybe a cool App for the Playstore too).
Thank you for the attention.
Lostion said:
Hello guys first of all I'm new here so i hope i make everything correct and I'm in the right section.
I just searched for the Stock S3 Gallery (the same like Note 2 with Gallery Flow Effect) but I couldn't find somehting that runs on AOSP Roms, so I just googled a little bit and found these Code (Source was stackoverflow.com, sorry but I can't post the links because Forum Rules with 10 Posts).
Code:
gal_caterories.setAdapter(new CategoryPreferenceAdapter (context,
response.customOfferPojo.offerAvailableCategories,1));
public class CategoryPreferenceAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
public static List<String> thumbnailsselection;
private ViewHolder holder = new ViewHolder();
private List<CategoriesClass> categories = new ArrayList<CategoriesClass>();
public static final int ACTIVITY_CREATE = 10;
public static List<Integer> prefferedCategories = new ArrayList<Integer>();
private int i = 0;
// Keep all Images in array
// public Integer[] mThumbIds = { R.drawable.pic_1, R.drawable.pic_2,
// R.drawable.pic_3, R.drawable.pic_4, R.drawable.pic_5,
// R.drawable.pic_6, R.drawable.pic_7, R.drawable.pic_8,
// R.drawable.pic_9, R.drawable.pic_10, R.drawable.pic_11,
// R.drawable.pic_12, R.drawable.pic_13, R.drawable.pic_14,
// R.drawable.pic_15 };
public CategoryPreferenceAdapter(Context c,
List<CategoriesClass> categories, List<Integer> prefferedCategories) {
this.mContext = c;
this.categories = categories;
this.prefferedCategories = prefferedCategories;
mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
thumbnailsselection = new ArrayList<String>();
}
class ViewHolder {
ImageView imageview;
TextView tv_categoryname;
// LinearLayout ll_category_selection;
CheckBox cb_check_category;
}
[user=439709]@override[/user]
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = mInflater
.inflate(R.layout.template_categories_grid, null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.iv_image_category);
holder.tv_categoryname = (TextView) convertView
.findViewById(R.id.tv_categoryname);
// holder.ll_category_selection = (LinearLayout) convertView
// .findViewById(R.id.ll_category_selection);
holder.cb_check_category = (CheckBox) convertView
.findViewById(R.id.cb_check_category);
if (prefferedCategories.contains(categories.get(position).categoryid)) {
holder.cb_check_category.setChecked(true);
} else {
holder.cb_check_category.setChecked(false);
holder.cb_check_category.setBackgroundColor(Color.TRANSPARENT);
}
holder.tv_categoryname.setText(categories.get(position).category
.toUpperCase());
holder.cb_check_category
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
prefferedCategories.add(categories.get(position).categoryid);
} else {
holder.cb_check_category
.setBackgroundColor(Color.TRANSPARENT);
prefferedCategories.remove(categories.get(position).categoryid);
}
}
});
ImageLoader imageload = new ImageLoader(mContext);
imageload.DisplayImage(
categories.get(position).defaultCategoryImage.toString(),
holder.imageview);
holder.imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
return convertView;
}
[user=439709]@override[/user]
public int getCount() {
// TODO Auto-generated method stub
return categories.size();
}
[user=439709]@override[/user]
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
[user=439709]@override[/user]
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}
Can someone maybe build an App with this Code? I ask because I have no clue about that, but I think the sourcecode is good and many guys would be happy. Maybe some Guy has the time to do it? (It is maybe a cool App for the Playstore too).
Thank you for the attention.
Click to expand...
Click to collapse
Me too .Looking for the same thing for a long time.
But could not find any.:crying:
Just wishing some guy to build an apk that would run on all phones like some other games.
Keep searching and kindly share if you find any.:good:
Thanks
Thank you man for posting this i think a lot of us wish to get this app on cyanogenmod for example i hope there's a hero dev. Can do this for us
Regards
تم الإرسال من جهازي GT-I9300 بواسطة تاباتلك 4 now Free
Hi! So Im about to release two versions of my app, one free with ads and one for 99cent. I followed Marios instuctions on how to add AdMob for Libgdx so I ended up with this:
Code:
public class MainActivity extends AndroidApplication implements IActivityRequestHandler {
protected AdView adView;
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
protected Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case SHOW_ADS:
{
adView.setVisibility(View.VISIBLE);
break;
}
case HIDE_ADS:
{
adView.setVisibility(View.GONE);
break;
}
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new Game(this), false);
// Create and setup the AdMob view
adView = new AdView(this, AdSize.BANNER, "secretKey"); // Put in your secret key here
adView.loadAd(new AdRequest());
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}
@Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
}
My question is, since Im going to have a adfree version and I want to make it as easy as possible, can I just call "handler.showAds(false);" to completely dissable ads in the paid version or should I completely remove everything that have to do with the ads? I don't know much about how the ads works and Im afraid there will be some mix up since I read something about impressions might go wrong and stuff
I changed it to this, will this work?
Code:
public class MainActivity extends AndroidApplication implements IActivityRequestHandler {
protected AdView adView;
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
private boolean isBought = false;
protected Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case SHOW_ADS:
{
adView.setVisibility(View.VISIBLE);
break;
}
case HIDE_ADS:
{
adView.setVisibility(View.GONE);
break;
}
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new Game(this, isBought), false);
// Create and setup the AdMob view
if(!isBought){
adView = new AdView(this, AdSize.BANNER, "Secret Key"); // Put in your secret key here
adView.loadAd(new AdRequest());
}
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
if(!isBought){
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
}
// Hook it all up
setContentView(layout);
}
@Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
}
Okay, so I have the fix for this, but I have another problem now. I had to create two different android projects (both linked to the main source of the game) with a ".free" at the free versions packaging name in the AndroidManifest, because you cant have two apps with the same packaging on Google Play. But this makes it so that the user have to restart everything if they upgrade from the free version to paid version.
All I want to is that I could save the preference file to a specific place (so it wont get removed if the free version gets removed) and make the paid version read it. And Im using LibGdx btw Smiley
EDIT:
I have tried doing it now with using Context. I'm able to find the preference file, but it's not able to get the contents from the preference file itself, since it always returns 0 (the default value). Is this because I use LibGdx? I have read that LibGdx saves its own preference files as SharedPreferences on Android so that shouldn't be the issue.
Code:
public void tryLoadPrefs(){
Context otherAppsContext = null;
try {
otherAppsContext = createPackageContext("com.mayogames.zombiecubes.free", 0);
} catch (NameNotFoundException e) {
System.out.println(e);
}
System.out.println("Extracting = " + otherAppsContext.getSharedPreferences("Settings", CONTEXT_IGNORE_SECURITY).getInt("seconds", 0));
}
Delta517 said:
Okay, so I have the fix for this, but I have another problem now. I had to create two different android projects (both linked to the main source of the game) with a ".free" at the free versions packaging name in the AndroidManifest, because you cant have two apps with the same packaging on Google Play. But this makes it so that the user have to restart everything if they upgrade from the free version to paid version.
All I want to is that I could save the preference file to a specific place (so it wont get removed if the free version gets removed) and make the paid version read it. And Im using LibGdx btw Smiley
EDIT:
I have tried doing it now with using Context. I'm able to find the preference file, but it's not able to get the contents from the preference file itself, since it always returns 0 (the default value). Is this because I use LibGdx? I have read that LibGdx saves its own preference files as SharedPreferences on Android so that shouldn't be the issue.
Code:
public void tryLoadPrefs(){
Context otherAppsContext = null;
try {
otherAppsContext = createPackageContext("com.mayogames.zombiecubes.free", 0);
} catch (NameNotFoundException e) {
System.out.println(e);
}
System.out.println("Extracting = " + otherAppsContext.getSharedPreferences("Settings", CONTEXT_IGNORE_SECURITY).getInt("seconds", 0));
}
Click to expand...
Click to collapse
EDIT: Im loading in the onCreate() method. Is that a problem?
Personally, the way I do it with libGDX is I create two projects. One with the adds and one without, like you said.
To solve the problem of not having two projects with the same package name, I change the second one. Then go into the android manifest file and change it there too. Then it should work.