I am getting the values and setting the adapter on onpostexecute() of my async task and when i click the items of listview in oncraete() Its showing nothing and I am trying to show a toast to test it.
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list);
new Ftpclient().execute();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Toast.makeText(getApplicationContext(), "clicked on", 500).show;
String f = "FILE54.pdf";
File file = new File(Environment
.getExternalStorageDirectory()
+ "/FtpFiles"
+ f);
if (file.exists()) {
Uri filepath = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(filepath, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"file not found", 500);
Log.e("error", "" + e);
}
}
}
});
class Ftpclient extends AsyncTask<String, Void, ArrayList<String>> {
ArrayList<String> temparrlist = new ArrayList<String>();
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(MainActivity.this, "Connecting",
"please wait");
}
protected ArrayList<String> doInBackground(String... connection) {
temparrlist = listftpitems();
return temparrlist;
}
protected void onPostExecute(ArrayList<String> result) {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_list_item_1,
result);
lv.setAdapter(arrayAdapter);
dialog.dismiss();
}
}
Help is always appreciated,Thanks
EDIT
ArrayList<String> temparrlist = new ArrayList<String>();
temparrlist = listftpitems();
String uri = temparrlist.get(position).toString();
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/FtpFiles" + "/" + uri);
if (uri.endsWith(".pdf") || uri.endsWith(".txt")) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"file not found", 500).show();
Log.e("error", "" + e);
}
This code...
Toast.makeText(getApplicationContext(), "clicked on", 500);
Should be like this...
Toast.makeText(getApplicationContext(), "clicked on", Toast.LENGTH_SHORT).show();
You have to use show() method to show toast notification.....
EDIT :
To use SPECIFIED TIME YOU CAN USE BELOW CODE..........
final Toast toast = Toast.makeText(getApplicationContext(), "clicked on", Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 500);
EDIT :
To Open PDF USE FOLLOWING CODE...THAT WORKS FOR ME...........BUT MAKE SURE THAT YOU HAVE PDF READER IN YOUR MOBILE............
btn_open.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
name = edt_filename.getText().toString(); // name of selected file...
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/documents" +"/"+ name+".pdf"); // going to directory
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
}
});
change you toast:Toast.makeText(getApplicationContext(), "clicked on"+position, 500).show();
Related
I want to send the integer value from one activity to another but I am not getting the value,There is no error in my project.If I am giving the static value it is working so problem with intent only..
Passing the data
try {
JSONObject jsonobject = new JSONObject(doc);
final String statusCode=jsonobject.get("code").toString();
System.out.print("Code......>>>>>>>>>>>>>>"+statusCode);
switch (statusCode){
case "400":
Toast.makeText(getApplicationContext(), "" + doc, Toast.LENGTH_LONG).show();
break;
case "200":
final Dialog dialog = new Dialog(SecondActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.link_dialog);
Button dialogButtonCustomercare = (Button) dialog
.findViewById(R.id.button_ok);
Button dialogButtonCustomer = (Button) dialog
.findViewById(R.id.button_contact_us);
dialogButtonCustomercare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SecondActivity.class);
i.putExtra("StatusCode", 200);
startActivity(i);
// dialog.dismiss();
}
});
dialogButtonCustomer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
makeCall(phonenumber);
}
});
dialog.show();
break;
default:
Toast.makeText(getApplicationContext(), "Oops something went wrong! ", Toast.LENGTH_LONG).show();
break;
}
} catch (Exception e) {
Log.i("Error", e.getMessage());
}
Getting the data
int responseCode ;
Intent i = getIntent();
responseCode = i.getIntExtra("StatusCode",0);
System.out.print("Status Code" + responseCode);
if (responseCode==200) {
DetailsImageView.setVisibility(View.VISIBLE);
// textview.settext(bank details verification done)
} else {
DetailImageView.setVisibility(View.INVISIBLE);
}
dialogButtonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SecondActivity.class);
i.putExtra("StatusCode", 200);
// Toast.makeText(getApplicationContext(), "sucessful intent" +200, Toast.LENGTH_LONG).show();
startActivity(i);
finish();
dialog.dismiss();
}
});
I have the following activity populating listview from SQLite.
When click on empty I delete table content correctly and refresh the CartActivity which appears empty.
If I add new element in my cart then old elements appears again but only in the listview and (correctly) not in my db. If I close the application the listview update itself correctly.
Tried to give a look at similar question, tried with notify but nothing happens. Someone wrote about "you delete the data but not the entries" but I'm not able to.
How could I solve this issue?
Any help would be much appreciated. Thanks in advance.
public class CartActivity extends Activity {
ListView list;
Context context;
SessionManagement session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
Typeface font = Typeface.createFromAsset(this.getAssets(), "font/VarelaRound-Regular.ttf");
context = getApplicationContext();
session = new SessionManagement(context);
final CartHandler db = new CartHandler(this);
Log.d("Reading: ", "Reading all contacts..");
final List<CartRow> products = db.getAllProducts();
for (CartRow cn : products) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Number: " + cn.getNumber() + " ,Pieces: " + cn.getPieces() + " ,Price: " + cn.getPrice() + " ,Tot: " + cn.getTotPrice();
Log.d("Nome: ", log);
}
if(products.isEmpty() ){
//Intent intent = new Intent(getApplicationContext(),MenuActivity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//startActivity(intent);
Toast.makeText(this, "", Toast.LENGTH_LONG).show();
//finish();
} else {
final CartHandler mdb = new CartHandler(this);
getItemsFromDatabase(mdb);
final CustomCarterList adapter = new CustomCarterList(CartActivity.this);
list = (ListView) findViewById(R.id.cart);
list.setAdapter(adapter);
Button empty = (Button) findViewById(R.id.emptycart);
empty.setTypeface(font);
empty.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
db.deleteAll();
//mdb.deleteAll();
Intent intent = new Intent(CartActivity.this, CartActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
Button proceed = (Button) findViewById(R.id.proceed);
proceed.setTypeface(font);
proceed.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!session.isLoggedIn()) {
Intent intent = new Intent(CartActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(
getApplicationContext(),
CheckoutActivity.class
);
startActivity(intent);
}
}
});
}
}
public void getItemsFromDatabase(CartHandler mdb) {
Cursor cursor = null;
try{
SQLiteDatabase db =mdb.getReadableDatabase();
cursor=db.rawQuery("select * from products", null);
while (cursor.moveToNext()){
Log.e("Cart", cursor.getString(1)+":"+cursor.getString(2)+":"+cursor.getString(3)+":"+cursor.getString(4)+":"+cursor.getString(5));
CartRow.itemIdList.add(cursor.getString(0));
CartRow.itemNameList.add(cursor.getString(1));
CartRow.itemQuantityList.add(cursor.getString(2));
if (cursor.getString(3).equals("0")){
CartRow.itemPiecesList.add("Pieces: 1");}
else{
CartRow.itemPiecesList.add("Pieces: "+cursor.getString(3));}
CartRow.itemPriceList.add(cursor.getString(4) + ".00€");
CartRow.itemTotPriceList.add(cursor.getString(5)+".00€");
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
use adapter.notifyDataSetChanged() instead of notify.
Change the else part of the onCreate method like this...
if(products.isEmpty() ){
//Intent intent = new Intent(getApplicationContext(),MenuActivity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//startActivity(intent);
Toast.makeText(this, "", Toast.LENGTH_LONG).show();
//finish();
} else {
final CartHandler mdb = new CartHandler(this);
getItemsFromDatabase(mdb);
final CustomCarterList adapter = new CustomCarterList(CartActivity.this);
list = (ListView) findViewById(R.id.cart);
list.setAdapter(adapter);
Button empty = (Button) findViewById(R.id.emptycart);
empty.setTypeface(font);
empty.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
db.deleteAll();
CartRow.itemIdList.clear(); // clears the list
adapter.notifyDataSetChanged(); // notifies adapter about the change.
//mdb.deleteAll();
Intent intent = new Intent(CartActivity.this, CartActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
Button proceed = (Button) findViewById(R.id.proceed);
proceed.setTypeface(font);
proceed.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!session.isLoggedIn()) {
Intent intent = new Intent(CartActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(
getApplicationContext(),
CheckoutActivity.class
);
startActivity(intent);
}
}
});
}
SOLVED:
Calling
CartRow.itemIdList.clear();
CartRow.itemNameList.clear();
CartRow.itemNumberList.clear();
CartRow.itemPiecesList.clear();
CartRow.itemPriceList.clear();
CartRow.itemTotPriceList.clear();
before
getItemsFromDatabase(mdb);
and after
db.deleteAll();
I have downloaded the files from ftp and saving in the sd card.So I want to show the files by fetching from the sd card with listview on click.But its not working for me.
Here is my code
public File f;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list);
new Ftpclient().execute();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String uri = f.toString(); // error here is null ponter exception
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/FtpFiles" + uri);
// if (uri.contains(".pdf")) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "file not found",
500).show();
Log.e("error", "" + e);
}
// }
// }
}
class Ftpclient extends AsyncTask<String, Void, ArrayList<String>> {
ArrayList<String> temparrlist = new ArrayList<String>();
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(MainActivity.this, "Connecting",
"please wait");
}
protected ArrayList<String> doInBackground(String... connection) {
temparrlist = listftpitems();
return temparrlist;
}
protected void onPostExecute(ArrayList<String> result) {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_list_item_1,
result);
lv.setAdapter(arrayAdapter);
dialog.dismiss();
}
}
shows NPE at this line
String uri = f.toString();
Help is always appreciated,Thanks
try with lv.invalidate() after lv.setAdapter(arrayAdapter) inside onPostExecute
The member File f is never initialized, so is defaulted to null. This is why a NPE is thrown when doing:
String uri = f.toString();
I have created a "Contact Us" page on my app and the idea is you have the option to send a picture to an already predetermind email address. The problem I have is its taking all the images from the gallery of the phone and sending them all in the email. All I want to do is send one picture. I cant seem to work out what to change to be able to just send one image. Is there anyone who could help?
Here is my code:
public class EmailActivity extends Activity {
Button send;
EditText address, subject, emailtext;
protected static final int CAMERA_PIC_REQUEST = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.email);
send=(Button) findViewById(R.id.emailsendbutton);
address=(EditText) findViewById(R.id.emailaddress);
subject=(EditText) findViewById(R.id.emailsubject);
emailtext=(EditText) findViewById(R.id.emailtext);
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if
(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
{
}
File pngDir = new File(
Environment.getExternalStorageDirectory(),
"Android/data/com.random.jbrefurb/quote");
if (!pngDir.exists())
pngDir.mkdirs();
Uri pngUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ "random#yahoo.co.uk"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject.getText());
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext.getText());
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, pngUri);
emailIntent.setType("image/jpeg");
EmailActivity.this.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
});
Button back = (Button) findViewById(R.id.button1);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// fire intent
finish(); // finish current activity
Intent austinIntent = new Intent(view.getContext(),
ContactActivity.class);
startActivityForResult(austinIntent, 0);
}
});
Button camera = (Button) findViewById(R.id.button2);
camera.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
;
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode== 0 && resultCode == Activity.RESULT_OK){
Bitmap x = (Bitmap) data.getExtras().get("data");
((ImageView)findViewById(R.id.imageView1)).setImageBitmap(x);
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.BUCKET_ID, "test");
values.put(Images.Media.DESCRIPTION, "test Image taken");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(uri);
x.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
outstream.close();
} catch (FileNotFoundException e) {
//
}catch (IOException e){
//
}
} }
}
Many thanks in advance
this is code i used in my application try if you need help..
private OnClickListener shareemail=new OnClickListener(){
#Override
public void onClick(View v) {
String address = "your emailaddress";
File filee;
if(address.length()==0)
{
AlertDialog.Builder ab=new AlertDialog.Builder(null);
ab.setMessage("Email Address must not be empty!");
ab.setPositiveButton("OK", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
ab.show();
}
else
{
ArrayList<Uri> uris = new ArrayList<Uri>();
Uri u;
Intent emailSession = new Intent(Intent.ACTION_SEND_MULTIPLE);
emailSession.putExtra(Intent.EXTRA_SUBJECT,"your subject");
emailSession.setType("images/*");
emailSession.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {address});
emailSession.putExtra(android.content.Intent.EXTRA_TEXT,"body text");
FileWriter fw;
BufferedWriter bw;
try{
filee = new File(path of image you want to send);
if(filee.exists())
{
Uri u1 = Uri.fromFile(filee);
uris.add(u1);
emailSession.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(emailSession);
}
}
catch (ActivityNotFoundException e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}}
};
I am wondering if my codes here can view a specific pdf file using existing PDF viewer in Android Phone (HTC Desire).. If i would like to open pdf files from local folder.. What should i do?
public class ghcm_Submenu1 extends Activity {
private ListView lv1;
private String lv_arr[]= {"item1", "item2"};
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.submenu);
lv1=(ListView)findViewById(R.id.ListView01);
// By using setAdpater method in listview we an add string array in list.
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parentView, View childView, int position, long id) {
if ((position)== 0){
Intent intent = new Intent();
File file = new File("/sdcard/item1.pdf");
if (file.exists()) {
Uri path = Uri.fromFile(file);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(ghcm_Submenu1.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
else if ((position)== 1){
Intent intent = new Intent();
File file = new File("/sdcard/item2.pdf");
if (file.exists()) {
Uri path = Uri.fromFile(file);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(ghcm_Submenu1.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
}
public void onNothingSelected(AdapterView parentView) {
}
});
}
}