I am trying to display my text file on clicking continue button when dialog appears. This is how far i have done. When i click "Continue" button it isn't showing any text in dialog.
My text file is saved on desktop.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OnLoad(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please read carefully!");
builder.setIcon(R.drawable.news);
builder.setCancelable(false);
builder.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
try {
FileInputStream fin =openFileInput("bloodline.txt");
InputStreamReader insr = new InputStreamReader(fin);
int i = 0;
String str = "";
while ((i = insr.read()) != -1) {
str = str + (char) i;
}
Toast.makeText(getBaseContext(), " " + str,
Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
System.out.println("File Not available " + e.getMessage());
Toast.makeText(getBaseContext(),
"File Not available " + e.getMessage(), Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getBaseContext(), "IO Exception " + e.getMessage(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
);
builder.setNegativeButton("Declined", new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getBaseContext(), "You have declined",
Toast.LENGTH_SHORT).show();
}
});
}
}
Thanks in advance.
It would be better if you just go through some of these links that I'm listing below,then you'll have the basic idea of how to create dialog depending upon your needs.
Link 1: Which is a nice example from android.developer's site and recommended.
Link 2: Popular android tutorials from Vogella
Link 3: This link will be explaining you to create Custom Dialogs.
Link 4: Overview of creating dialog from android developers
Link 5: From AndroidHive
I hope this will help you a lot.
Related
I have problem in my application.
I want to show user's profile, and I have two links in my app.
One link is via TextView, which run showUser(View v) method:
public void showUser(View v){
Intent i;
i=new Intent(getApplicationContext(), ShowProfile.class);
i.putExtra("id",user); // user is String with users ID
startActivity(i);
}
And the second link is in dialog, which user can open:
( I will post here whole method, but I'll highlight important part )
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder .setTitle(R.string.show_photo_show_rated_users_title)
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
ListView modeList = new ListView(this);
String[] stringArray = new String[ratedUsers.size()];
for ( int i=0 ; i<ratedUsers.size() ; i++ ){
stringArray[i] = ratedUsers.get(i).get("name");
}
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, R.layout.dropdown_item_white, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);
modeList.setOnItemClickListener(new ListView.OnItemClickListener(){
/*********************** IMPORTANT PART *********************************/
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int index,long arg3) {
Intent i;
i=new Intent(ShowPhotoDetails.this , ShowProfile.class);
i.putExtra("id",ratedUsers.get(index).get("id"));
/**** ratedUsers is ArrayList<HashMap<String,String>> ****/
startActivity(i);
}});
builder.setView(modeList);
final Dialog dialog = builder.create();
dialog.show();
}
And finally here's ShowProfile.class:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
Intent i = getIntent();
try {
id = i.getStringExtra("id");
}catch(Exception e){
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error loading intent", Toast.LENGTH_SHORT).show();
finish();
}
try{
Log.w("ID",id); //always give right number
new GetUserInformations().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, id);
/*
If I comments this asyncTask, there's no error at all, but if I run it, It
open debug View in Eclipse, says that "Source not found" and crashes...
No LogCat Output
*/
}catch(Exception e){
e.printStackTrace();
}
...
I wonder why in one case it run perfectly and in the other it crashes. As I wrote in code, there's no LogCat output for this crash. It don't even say Uncaught exception or something like this.
EDIT: I found out what gives me the error.
public class GetUserInformations extends AsyncTask<String,Void,Void>{
Map<String,Object> tmpUser;
#Override
protected void onPreExecute(){
tmpUser = new HashMap<String,Object>();
}
#Override
protected Void doInBackground(String... arg) {
try{
int u_id = Integer.parseInt(arg[0]);
tmpUser = myDb.getUser(u_id); // downloading info
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void arg){
if ( tmpUser != null ){
Log.w("LOG",""+tmpUser.get("name"));
name = (String) tmpUser.get("name");
fbId = (String) tmpUser.get("id");
email = (String) tmpUser.get("email");
country = (Integer) tmpUser.get("country");
userName.setText(name);
profilepic.setProfileId(fbId);
userSubscribe.setVisibility(View.VISIBLE);
}
else {
Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_SHORT).show();
finish();
}
}
}
When I open activity for first time, everything downloads fine, but when I backPress and click on link to this Activity again, then it gives me NullPointerException.
Do you know why ?
In your onItemClick function, try to put :
i = new Intent(getApplicationContext(), ShowProfile.class);
instead of :
i = new Intent(ShowPhotoDetails.this, ShowProfile.class);
remove this:
new GetUserInformations().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, id);
and use :
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
new GetUserInformations().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, id);
}
else {
new GetUserInformations().execute(id);
}
What is the API level on which you are facing this problem. Try to run it on different levels, taking Honeycomb as a reference.
Need to check the same and apply execute or executeONExecutor like this:
if (currentApiVersion >=
android.os.Build.VERSION_CODES.HONEYCOMB) {
new YourAsynctask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
new YourAsynctask().execute();
}
Check this asynctask-threading-regression-confirmed blog post
I am developing an app which has google in app purchase. There is a button buy now and after clicking the button I have to call inapp purchase but here is the problem I am facing, the buy now button is in an adapter class hence how can I do inapp purchase in an adapter class
here is my code
public void onClick(View v) {
switch (v.getId()) {
case R.id.loadmore_btn:
// call a url with ofset & limit with Thread
if (getbookItems.getContentName() == "LoadMore") {
booksItemsInfo.remove(booksItemsInfo.size() - 1);
}
if (UIAndDataLoader.offset < bookcategoryItem.getCount()) {
if (UIAndDataLoader.offset < DBTotalContentCount) {
UIAndDataLoader.offset = UIAndDataLoader.offset + 10;
UIAndDataLoader.loadFlag = 0;
myActivity.Tostart();
} else {
myActivity.URLConfig = MagURLConfig.bURL
+ MagURLConfig.uMAILIDNAME
+ _Settings.getString("setEmail-ID", null)
+ MagURLConfig.uPASSWORD
+ _Settings.getString("setPassword", null)
+ MagURLConfig.CATEGORYID
+ bookcategoryItem.getCatId() + MagURLConfig.OFFSET
+ DBTotalContentCount + MagURLConfig.LIMIT;
UIAndDataLoader.bookcountlimit = 1;
myActivity.toStartRefresh(true);
}
}
break;
case R.id.btn_buynow:
// System.out.println("this is buy btn------------->");
BookDataLoader.ActionButtonOnclick(btn_txt, action_btn,
getbookItems, "");
break;
case R.id.preview:
BookDataLoader.ActionButtonOnclick(btn_txt, action_btn,
getbookItems, "Preview");
break;
}
}
}
You can declare the adapter class in the same activity.thats why you can user mHelper object.
I done the same functionality in one of application for in puchase item.
like:-
holder.relative_layout_btn_buy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
if(isOnline())
mHelper.launchPurchaseFlow(OnlineStoreList.this,"android.test.purchased",RC_REQUEST,mPurchaseFinishedListener, "");
else
{
NetworkAlert();
}
} catch (Exception e) {
// Toast.makeText(getApplicationContext(),"Please wait...Try after some time!! " ,1).show();
Log.e("Exception", "===>" + e.toString());
complain(e.getMessage());
}
}
});
I hope with will help.Thanks!!
I'm developing an app which will do multiple method in a single input. For example calculating square circumference and area, I give only one EditText and two button. But when I run the app, if I give an input and click the area button it won't do the calculation until I click the circumference button. And same goes if I change the input. Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.square);
etSide = (EditText) findViewById(R.id.etSquare);
tvResult = (TextView) findViewById(R.id.tvSquare);
Button btnCir = (Button) findViewById(R.id.btnSqrCir);
btnCir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCir();
}
});
Button btnArea = (Button) findViewById(R.id.btnSqrArea);
btnArea.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
countArea();
}
});
}
private void countArea() {
try {
side = etSide.getText().toString();
s = parseInt(side);
area = s * s;
tvResult.setText("Area = " + cir);
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
private void countCir() {
try {
side = etSide.getText().toString();
s = parseInt(side);
cir = 4 * s;
tvResult.setText("Circumference = " + area);
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
Any better idea? Really need help...
It looks like you have your variables backwards. For example:
private void countArea() {
try {
side = etSide.getText().toString();
s = parseInt(side);
area = s * s;
tvResult.setText("Area = " + cir); // <-- here cir doesn't have a value until you click the circumference button
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
So your TextView would display ""Area = ""
It looks to me like you want
tvResult.setText("Area = " + cir);
to be
tvResult.setText("Area = " + area);
Let me know if I'm not understanding you correctly
Note:
For your Toast you should use this or YourActivityName.this for Context instead of getApplicationContext()
One other suggestion I might make since your onClick()s only call a method, to make it simpler you could use one listener like this
public void onCreate(...)
{
...
btnCir.setOnClickListener(this);
btnArea.setOnClickListener(this);
...
}
public void onClick(View v)
{
switch(v.getId()) // get the id of the Button clicked
{
case (R.id.btnSqrArea): // call appropriate method
countArea();
break;
case (R.id.btnSqrCir):
countCir();
break;
}
}
You would just have to remember to add implements OnClickListener to your class definition. That's just a preference but worth mentioning.
I have a file list with a longclicklistener that brings up a context menu with delete and rename options. These launch either a deleteDialog() or renameDialog(). These call either delete() or rename(). The delete works but rename is giving:
05-05 10:26:44.105: W/System.err(19017884): java.io.FileNotFoundException: Failed to rename file: /sdcard/My Webs/new/index.php
Even thought I can see this file on the filesystem at this location.
Here is my code for the Alerts:
void delete(File f) throws IOException {
if (f.isDirectory()) {
for (File c : f.listFiles())
delete(c);
}
if (!f.delete())
throw new FileNotFoundException("Failed to delete file: " + f);
}
void rename(File f, String newName) throws IOException {
File newFile = new File(newName);
f.renameTo(newFile);
if (!f.renameTo(newFile))
throw new FileNotFoundException("Failed to rename file: " + f);
}
public void delDialog(int position) {
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(R.drawable.remove);
alertDialog.setTitle(getString(R.string.delete));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String selectedFileString = directoryEntries.get(pos).getText();
File tmpFile = new File(currentDirectory.toString()
+ selectedFileString);
try {
delete(tmpFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
directoryEntries.remove(pos);
itla.notifyDataSetChanged();
currentFile = null;
changed = false;
return;
}
});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setMessage("Are you sure you want to delete this file?");
alertDialog.show();
}
public void renameDialog(int position) {
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(R.drawable.renameicon);
alertDialog.setTitle(getString(R.string.rename));
alertDialog.setButton("Rename", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String selectedFileString = directoryEntries.get(pos).getText();
File tmpFile = new File(currentDirectory.toString()
+ selectedFileString);
try {
rename(tmpFile, "test.html");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
itla.notifyDataSetChanged();
return;
}
});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setMessage("Are you sure you want to rename this file?");
alertDialog.show();
}
public void Show_Context(Context context, String message, int position) {
final AlertDialog customDialog = new AlertDialog.Builder(this).create();
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.contextmenu, null);
final Button del = (Button) view.findViewById(R.id.delBtn);
final Button rename = (Button) view.findViewById(R.id.renameBtn);
final int pos = position;
customDialog.setView(del);
customDialog.setView(rename);
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
delDialog(pos);
}
});
rename.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
renameDialog(pos);
}
});
customDialog.setView(view);
customDialog.show();
}
As you can see the code for the deleteDialog() and renameDialog() is the same yet the renameDialog() throws the FileNotFoundException
Have you tried fully qualifying the filename of the destination? You're currently attempting to rename to "test.html" from currentDirectory.toString()+selectedFileString.
You probably want to try currentDirectory.toString()+"test.html" as you might be running into permissions issues otherwise.
You call f.renameTo(newFile) two times! One time normally, and a second time within the if() condition. I guess it already gets renamed the first time, so when you do it a second time, it fails (either because the file doesn't have the same name anymore or because it already has the new filename).
f.renameTo(newFile);
if (!f.renameTo(newFile)) {...}
Try and remove the first .f.renameTo().
Also note, that renameTo() returning false can have all kinds of reasons, not just that the file cannot be found. And of course you get the FileNotFoundException because you throw it yourself in your code :-)
I am trying to test a simple file i/o program on android where i type in some text in
EditText and when i click the Save Button, it writes the content in a file. and when i click the Load button it loads the content back into the EditText.
here is my code---
public class Activity2 extends Activity {
private EditText textBox;
private static final int READ_BLOCK_SIZE = 100;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
textBox = (EditText) findViewById(R.id.txtText1);
Button saveBtn = (Button) findViewById(R.id.btnSave);
Button loadBtn = (Button) findViewById(R.id.btnLoad);
saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str = textBox.getText().toString();
try
{
PrintWriter PR=new PrintWriter(new File("text1.txt"));
PR.write(str);
PR.flush();
PR.close();
//textBox.setText("");
//---display file saved message---
Toast.makeText(getBaseContext(),
"File saved successfully!",
Toast.LENGTH_SHORT).show();
//---clears the EditText---
textBox.setText("");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
});
loadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try
{
File f=new File("text1.txt");
BufferedReader BR=new BufferedReader(new FileReader(f));
String txt="";
String str;
while((str=BR.readLine())!=null)
{
txt+=str;
}
//---set the EditText to the text that has been
// read---
textBox.setText(txt);
BR.close();
Toast.makeText(getBaseContext(),
"File loaded successfully!",
Toast.LENGTH_SHORT).show();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
}
}
`
why is it not working? Thanks in advance for any help. Any explanation would be highly appreciated.
Using new File("text1.txt") as output does not work on Android. The current working directoy is always / which is not writable for your app. Use
File f = new File(Environment.getExternalStorageDirectory(), "text1.txt");
getExternalStorageDirectory() is the internal storage for newer phones.
Your app Context has several paths that you can use if you want to store data in your app-private folder. Paths from Environment are in public places where you can simply read the data with a filemanager
And don't forget to add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in case you want to write to those public paths