I am getting image from server and display it in my application,and I download that image and downloading is working fine,but when I check my gallery image is not showing there,then in dev tools-Media Scanner I scan my SD card and again check my gallery and then image is showing..so how can I solve it..even I tried it Samsung phone,but with device i need to reboot my device...following is my snippet code...
public class bBusinessCardDL extends Activity{
String[] NAMES = new String[1];
String[] CurID = new String[1];
String[] Detail = new String[1];
String[] Photo = new String[1];
ListView listview;
String BCard;
ImageView image;
Button btnDownload;
ProgressDialog mProgressDialog;
private String Id;
private ImageView bcks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_bu_dl);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + "/mnt/sdcard/")));
bcks=(ImageView)findViewById(R.id.bck_from_bcard);
bcks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intss=new Intent(bBusinessCardDL.this,FirstPage.class);
startActivity(intss);
}
});
Id=this.getIntent().getStringExtra("userids");
System.out.println("checkd advertisement "+Id);
FillData();
btnDownload = (Button) findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDownloadAndSave();
Toast msgd = Toast.makeText(getBaseContext(),
"Business card Downloaded..!", Toast.LENGTH_LONG);
msgd.show();
}
});
}
public void mDownloadAndSave() {
File f = new File("/mnt/sdcard/" + Id
+ ".jpg");
//"/mnt/sdcard/"
InputStream is;
try {
is = new URL(BCard).openStream();
// Set up OutputStream to write data into image file.
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MediaScannerConnection.scanFile(this, new String[] { "ur_file_path" },
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 2048;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
public static String getJsonFromServer(String url) throws IOException {
BufferedReader inputStream = null;
URL jsonUrl = new URL(url);
URLConnection dc = jsonUrl.openConnection();
dc.setConnectTimeout(5000);
dc.setReadTimeout(5000);
inputStream = new BufferedReader(new InputStreamReader(
dc.getInputStream()));
// read the JSON results into a string
String jsonResult = inputStream.readLine();
return jsonResult;
}
static class ViewHolder {
TextView VHName;
ImageView VHPhoto;
int position;
}
public void FillData() {
String url = "";
url = "http://www.asdffsfd.com/web-service/b_card.php?user_id="
+ Id;
String jsonString;
jsonString = "";
try {
jsonString = getJsonFromServer(url);
} catch (IOException e) {
}
BCard = "";
try {
JSONArray earthquakes = new JSONArray(jsonString);
NAMES = new String[earthquakes.length()];
Photo = new String[earthquakes.length()];
for (int i = 0; i < earthquakes.length(); i++) {
JSONObject e = earthquakes.getJSONObject(i);
NAMES[i] = e.getString("b_card");
BCard = "http://" + e.getString("b_card");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
BCard = BCard.replace("\\", "");
BCard = BCard.replace(" ", "%20");
ImageView i = (ImageView) findViewById(R.id.BUCARD);
Log.d("Bcard", BCard);
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
BCard).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
after save the image, use below code for scanning file:
MediaScannerConnection.scanFile(this, new String[] { f.getAbsolutePath()},
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
Related
I am developing the android application in which sever sends the command to client and client side works on command and sends the result.
I am using handler in client side on every 15 sec to write the data on server side.
My problem is i am getting the output from client side and toasted correctly but the value is assigning to Textview first time which comes from client when the second time the value comes its getting toasted correctly but not assigning to Textview
Here my code Goes
Server Side
public class ServerSocketNew extends ActionBarActivity {
static final int SocketServerPORT = 8080;
LinearLayout chatpanel, sendpanel;
TextView infoIp, infoPort, chatMsg,contact,contact1;
Button b1,b2,back,Files;
EditText e1,e2;
private File root;
private ArrayList<File> fileList = new ArrayList<File>();
String msgLog = "";
String prev="";
String Message="Hies";
String Flags="Trues";
List<ChatClient> userList;
int count=0;
ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_socket_new);
infoIp = (TextView) findViewById(R.id.infoip);
infoPort = (TextView) findViewById(R.id.infoport);
chatMsg = (TextView) findViewById(R.id.chatmsg);
b1 = (Button) findViewById(R.id.send);
b2 = (Button) findViewById(R.id.Contacts);
e1 = (EditText) findViewById(R.id.say);
e2 = (EditText) findViewById(R.id.Something);
contact=(TextView) findViewById(R.id.contact);
contact1=(TextView) findViewById(R.id.contact1);
infoIp.setText(getIpAddress());
chatpanel = (LinearLayout)findViewById(R.id.chatpanel);
sendpanel = (LinearLayout)findViewById(R.id.sendpanel);
back=(Button) findViewById(R.id.back);
Files=(Button) findViewById(R.id.Files);
OnClickListener listener=new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Message=e1.getText().toString();
Flags="Trues";
count=0;
}
};
OnClickListener Listnerfiles=new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Message="";
Message="Files";
Flags="Trues";
sendpanel.setVisibility(View.GONE);
chatpanel.setVisibility(View.VISIBLE);
count=0;
}
};
OnClickListener listener1=new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Flags="Trues";
Message="CONTACTS";
sendpanel.setVisibility(View.GONE);
chatpanel.setVisibility(View.VISIBLE);
count=0;
}
};
b1.setOnClickListener(listener);
b2.setOnClickListener(listener1);
Files.setOnClickListener(Listnerfiles);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
e1.setText("");
Message="CONTACTS";
Flags="Trues";
count=0;
}
});
userList = new ArrayList<ChatClient>();
ChatServerThread chatServerThread = new ChatServerThread();
chatServerThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class ChatServerThread extends Thread {
#Override
public void run() {
Socket socket = null;
try
{
serverSocket = new ServerSocket(SocketServerPORT);
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
ChatClient client = new ChatClient();
userList.add(client);
ConnectThread connectThread = new ConnectThread(client, socket);
connectThread.start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
private class ConnectThread extends Thread {
Socket socket;
ChatClient connectClient;
String msgToSend = "";
ConnectThread(ChatClient client, Socket socket){
connectClient = client;
this.socket= socket;
client.socket = socket;
client.chatThread = this;
}
#Override
public void run() {
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
String n = dataInputStream.readUTF();
connectClient.name = n;
msgLog += connectClient.name + " connected#" +
connectClient.socket.getInetAddress() +
":" + connectClient.socket.getPort() + "\n";
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoIp.setText(msgLog);
}
});
dataOutputStream.writeUTF("Welcome " + n + "\n");
dataOutputStream.flush();
broadcastMsg(n + " join our chat.\n");
while (true) {
if (dataInputStream.available() > 0) {
String newMsg = dataInputStream.readUTF();
msgLog="";
msgLog = newMsg;
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// infoIp.setText(msgLog);
// Toast.makeText(getApplicationContext(), "prev="+prev, Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "messagelog="+msgLog, Toast.LENGTH_LONG).show();
Log.e("Number",msgLog);
e2.setText(msgLog+"#"+msgLog);
if(count<5)
{
Toast.makeText(getApplicationContext(), "messagelog="+msgLog, Toast.LENGTH_LONG).show();
contact.setText(msgLog);
}
count=count+1;
}
});
broadcastMsg(n + ": " + newMsg);
}
if(!msgToSend.equals("")){
dataOutputStream.writeUTF(msgToSend);
dataOutputStream.flush();
msgToSend = "";
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
userList.remove(connectClient);
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ServerSocketNew.this,
connectClient.name + " removed.", Toast.LENGTH_LONG).show();
msgLog += "-- " + connectClient.name + " leaved\n";
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoIp.setText(msgLog);
}
});
broadcastMsg("-- " + connectClient.name + " leaved\n");
}
});
}
}
private void sendMsg(String msg){
msgToSend = msg;
}
}
private void broadcastMsg(String msg){
for(int i=0; i<userList.size(); i++){
userList.get(i).chatThread.sendMsg(Message);
msgLog = Message+"\n";
}
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoIp.setText(msgLog);
}
});
}
My client side Code
public class CLIENTNEW123 extends ActionBarActivity {
static final int SocketServerPORT = 8080;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
LinearLayout loginPanel chatPanel;TextView chatMsg;static String fourth;
Button buttonSend;
String msgLog = "";
String msgLog1="";
String ret = null;
String nameno="";
String ret1 = null;
Context context=this;
String name="";
String flags="false";
ChatClientThread chatClientThread = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clientnew123);
final Handler handler = new Handler();
loginPanel = (LinearLayout)findViewById(R.id.loginpanel);
chatPanel = (LinearLayout)findViewById(R.id.chatpanel);
chatMsg = (TextView) findViewById(R.id.chatmsg);
msgLog = "";
chatMsg.setText(msgLog);
loginPanel.setVisibility(View.GONE);
chatPanel.setVisibility(View.VISIBLE);
chatClientThread = new ChatClientThread(
"aaa","192.168.43.1", SocketServerPORT);
chatClientThread.start();
Runnable runable = new Runnable() {
#Override
public void run() {
try{
chatClientThread.sendMsg("Namasted"+ "\n");
handler.postDelayed(this, 15*1000);
Log.e("In Handler", "In Handler");
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable
handler.postDelayed(this, 15*1000);
}
}
};
handler.postDelayed(runable, 15*1000);
}
private class ChatClientThread extends Thread {
String name;
String dstAddress;
int dstPort;
String msgToSend = "";
boolean goOut = false;
private File root;
private ArrayList<File> fileList = new ArrayList<File>();
private LinearLayout view;
String Filenames="";
File[] fileArray;
ChatClientThread(String name, String fourth, int port) {
this.name = name;
dstAddress = fourth;
dstPort =8080;
}
#Override
public void run() {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(name);
dataOutputStream.flush();
while (!goOut) {
if (dataInputStream.available() > 0) {
msgLog1 = dataInputStream.readUTF();
// msgLog += msgLog1;
// Toast.makeText(getApplicationContext(),msgLog,Toast.LENGTH_LONG ).show();
CLIENTNEW123.this.runOnUiThread(new Runnable() {
#Override
public void run() {
chatMsg.setText(msgLog1);
// name=msgLog;
//abcd aa=new abcd();
//aa.add(name);
}
});
//sendMsg("name " + "\n");
}
if(!msgToSend.equals("")){
if(msgLog1.equals("FilesNew"))
{
File file = new File(Environment.getExternalStorageDirectory(),"test.txt");
byte[] bytes = new byte[1024];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
bos.close();
socket.close();
}
if(msgLog1.equals("Files"))
{
flags="Files";
root = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath());
fileList=getfile(root);
for (int i = 0; i < fileList.size(); i++) {
Filenames+=fileList.get(i).getName()+"#"+"\n";
System.out.println(fileList.get(i).getName());
if (fileList.get(i).isDirectory()) {
}
}
dataOutputStream.writeUTF(Filenames+"\n");
dataOutputStream.flush();
}
else if(msgLog1.equals("CONTACTS"))
{
flags="true";
dataOutputStream.writeUTF("\n");
dataOutputStream.flush();
}
else if(flags=="true")
{
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'"+msgLog1+"%'";
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, null, null);
int indexName = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// Socket socket = serverSocket.accept();
while(c.moveToNext()) {
ret = c.getString(indexName);
ret1 = c.getString(indexNumber);
nameno=nameno+" "+ret+" "+ret1;
}
if (c.moveToFirst()) {
ret = c.getString(0);
ret1 = c.getString(0);
}
c.close();
dataOutputStream.writeUTF(nameno+"\n");
dataOutputStream.flush();
}
else
{
dataOutputStream.writeUTF("Messgae lo"+msgLog1);
dataOutputStream.flush();
}
msgToSend = "";
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
CLIENTNEW123.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText( CLIENTNEW123.this, eString, Toast.LENGTH_LONG).show();
}
});
}
catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
CLIENTNEW123.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText( CLIENTNEW123.this, eString, Toast.LENGTH_LONG).show();
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
CLIENTNEW123.this.runOnUiThread(new Runnable() {
#Override
public void run() {
loginPanel.setVisibility(View.VISIBLE);
chatPanel.setVisibility(View.GONE);
}
});
}
}
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
fileList.add(listFile[i]);
getfile(listFile[i]);
} else {
if (listFile[i].getName().endsWith(".png")
|| listFile[i].getName().endsWith(".jpg")
|| listFile[i].getName().endsWith(".jpeg")
|| listFile[i].getName().endsWith(".gif")
|| listFile[i].getName().endsWith(".mp3")
|| listFile[i].getName().endsWith(".pdf"))
{
fileList.add(listFile[i]);
}
}
}
}
return fileList;
}
private void sendMsg(String msg){
msgToSend = msg;
}
private void disconnect(){
goOut = true;
}
}
}
I toasted my string in run method of connectthread class
like
Toast.makeText(getApplicationContext(), "messagelog="+msgLog, Toast.LENGTH_LONG).show();
And after that i am assigning the value to the textview
I am getting the correct value in toast.
i am getting the problem at server side near
if(count<5)
{
Toast.makeText(getApplicationContext(), "messagelog="+msgLog, Toast.LENGTH_LONG).show();
contact.setText(msgLog);
}
this code
In 'contact' textview i am setting the value
Thanks in advance
Since you are using msgLog in UIThread,
thus its value replace when this thread repeat run method.
try to append new value on msgLog not just replace it
msgLog="";
while (true) {
if (dataInputStream.available() > 0) {
String newMsg = dataInputStream.readUTF();
msgLog += newMsg;
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// infoIp.setText(msgLog);
// Toast.makeText(getApplicationContext(), "prev="+prev, Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "messagelog="+msgLog, Toast.LENGTH_LONG).show();
Log.e("Number",msgLog);
e2.setText(msgLog+"#"+msgLog);
if(count<5)
{
Toast.makeText(getApplicationContext(), "messagelog="+msgLog, Toast.LENGTH_LONG).show();
// Flags="False";
// contact.setText("");
// contact1.setText("");
//contact1.setText(msgLog2);
contact.setText(msgLog);
}
count=count+1;
}
});
broadcastMsg(n + ": " + newMsg);
}
When i am scrolling the GridView the images disappear in it. In log Cat its also showing outofmemory i dont know what i am doing wrong here.! It takes long time to display the images also. Thanks in Advance.
BaseActivity.java
public class BaseActivity extends Activity{
private Context context = this;
boolean server_connection = false;
static final Comparator<HashMap<String, String>> byDate = new Comparator<HashMap<String, String>>() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public int compare(HashMap<String, String> ord1, HashMap<String, String> ord2) {
Date d1 = null;
Date d2 = null;
try {
if(ord1.get("datetime")!=null){
d1 = sdf.parse(ord1.get("datetime"));
}
else{
d1 = sdf.parse("1970-01-01 00:00:00");
}
if(ord2.get("datetime")!=null){
d2 = sdf.parse(ord2.get("datetime"));
}
else{
d2 = sdf.parse("1970-01-01 00:00:00");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Log.d("Date", ""+d1+"..........."+d2);
return (d1.getTime() > d2.getTime() ? -1 : 1); //descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<HashMap<String, String>> byCount = new Comparator<HashMap<String, String>>() {
public int compare(HashMap<String, String> ord1, HashMap<String, String> ord2) {
int c1,c2;
if(ord1.get("download_count")!=null && !ord1.get("download_count").equals("null")){
c1=Integer.parseInt(ord1.get("download_count"));
}
else{c1=0;}
if(ord2.get("download_count")!=null && !ord2.get("download_count").equals("null")){
c2=Integer.parseInt(ord2.get("download_count"));
}
else{c2=0;}
return (c1>c2 ? -1 : 1); //descending
}
};
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public String prepareWebserviceRequest(String methodname, String[] keys, String[] values) throws JSONException{
String retStr = null;
String strParams = null;
JSONObject json = new JSONObject();
for(int i=0;i<keys.length;i++){
json.put(keys[i],values[i]);
}
JSONObject fJson = new JSONObject();
fJson.put("method_name", methodname);
fJson.put("body", json);
retStr = fJson.toString();
return retStr;
}
public String prepareWebserviceRequestOnlyMethod(String methodname) throws JSONException{
String retStr = null;
String strParams = null;
JSONObject json = new JSONObject();
JSONObject fJson = new JSONObject();
fJson.put("method_name", methodname);
// fJson.put("body", json);
retStr = fJson.toString();
return retStr;
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// RECREATE THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
class Download extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bmp=null;
bmp = getBitmapFromURL(params[0]);
return bmp;
}
}
public void WriteFile(String path,String filename,String data) {
try{
File direct = new File(path);
if(!direct.exists())
{
direct.mkdir();//directory is created;
}
String fpath= path +filename;
File txtfile=new File(fpath);
txtfile.createNewFile();
FileOutputStream fout=new FileOutputStream(txtfile);
OutputStreamWriter myoutwriter=new OutputStreamWriter(fout);
myoutwriter.write(data);
myoutwriter.close();
fout.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public String ReadFile(String path,String filename)
{ File myFile = new File(path + filename);
if(!myFile.exists())
{
return null;
}
FileInputStream fIn = null;
try {
fIn = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
try {
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return aBuffer;
}
public boolean FileExist(String filename)
{
String PATH2 = Environment.getExternalStorageDirectory() + "/"+Constant.Alert_Name+filename;
Log.v("log_tag initial path", "PATH: " + PATH2);
File file2 = new File(PATH2);
if(file2.exists()==true)
{
return true;
}
return false;
}
public String callAPI(String strRequest) {
String result = null;
String new_params;
int ResponseCode;
// TODO Auto-generated method stub
try {
JSONObject json = new JSONObject();
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
httpParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache-HttpClient/Android");
//httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
httpParams.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
HttpClient client = new DefaultHttpClient(cm,httpParams);
String url = Constant.WebService_URL;
//String url = "http://192.168.1.3/messages_app/main.php";
URL url1 = new URL(Constant.WebService_URL);
// URL url1 = new URL("http://192.168.1.3/messages_app/main.php");
HttpPost request = new HttpPost(url);
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
new_params =strRequest;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//nameValuePairs.add(new BasicNameValuePair("json","{\"method_name\":\"get_all_category\"}"));
nameValuePairs.add(new BasicNameValuePair("json",new_params));
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
ResponseCode = response.getStatusLine().getStatusCode();
//Log.d("ResponseCode", ""+ResponseCode);
if(ResponseCode==200){
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
result = RestClient.convertStreamToString(instream);
// Log.i("Read from server", result);
}
}
else if(ResponseCode!=200){
return "Server down";
}
} catch (Throwable t) {
return null;
}
return result;
}
}
LazyAdapter.java
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private String data[];
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
DisplayImageOptions options;
ArrayList<HashMap<String, String>> list;
public LazyAdapter(Activity a,ArrayList<HashMap<String, String>> list) {
this.list=list;
activity = a;
inflater = (LayoutInflater)LayoutInflater.from(a);
File cacheDir = StorageUtils.getOwnCacheDirectory(a, "Download");
// Get singletone instance of ImageLoader
imageLoader = ImageLoader.getInstance();
// Create configuration for ImageLoader (all options are optional)
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
// You can pass your own memory cache implementation
.memoryCacheExtraOptions(480,800)
.denyCacheImageMultipleSizesInMemory()
.discCacheExtraOptions(480, 480, CompressFormat.PNG, 100)
.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.enableLogging()
.build();
// Initialize ImageLoader with created configuration. Do it once.
imageLoader.init(config);
//imageLoader.init(ImageLoaderConfiguration.createDefault(a));
// imageLoader=new ImageLoader(activity.getApplicationContext());
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.cacheInMemory()
// .cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(20))
.build();
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if(convertView==null)
{
vh = new ViewHolder();
convertView= inflater.inflate(R.layout.other, parent,false);
vh.iv=(ImageView)convertView.findViewById(R.id.picture);
vh.pb= (ProgressBar)convertView.findViewById(R.id.pb);
vh.tv = (TextView)convertView.findViewById(R.id.text);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
// vh.tv.setText("Image in postion ="+position);
if(Global.getCurrent_tab()==1){
vh.tv.setText(""+list.get(position).get("download_count"));
}
display(vh.iv, Constant.img_URL+list.get(position).get("photo_name"), vh.pb);
return convertView;
}
public void display(ImageView img, String url, final ProgressBar pb)
{
imageLoader.displayImage(url, img, options, new ImageLoadingListener() {
#Override
public void onLoadingCancelled() {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(Bitmap arg0) {
// TODO Auto-generated method stub
pb.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(FailReason arg0) {
// TODO Auto-generated method stub
pb.setVisibility(View.GONE);
}
#Override
public void onLoadingStarted() {
// TODO Auto-generated method stub
pb.setVisibility(View.VISIBLE);
}
});
}
static class ViewHolder
{
ImageView iv;
TextView tv;
ProgressBar pb;
}
}
DefaultGridView.java
public class DefaultGridView extends Activity {
GridView gridView;
Context context=this;
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.latestphotos);
gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(new LazyAdapter(DefaultGridView.this,Global.getPhotos_list()));
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
String url =Constant.img_URL+Global.getPhotos_list().get(position).get("photo_name");
Intent i = new Intent(DefaultGridView.this, FullImageActivity.class);
i.putExtra("idkey", url); // pass the id
startActivity(i);
}
});
}
}
FullImageActivity.java
public class FullImageActivity extends Activity {
Button download, setaswallpaper, reportissue;
String url1;
Bitmap myBitmap;
ImageDownloader mDownloader;
FileOutputStream fos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
setaswallpaper = (Button) findViewById(R.id.setaswallpaper);
download = (Button)findViewById(R.id.download);
reportissue = (Button)findViewById(R.id.reportissue);
final ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
url1 = getIntent().getStringExtra("idkey"); //get id
Log.i(".............",""+url1);
//imageView.setImageResource(id);
new Thread( new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try
{
URL url = new URL(url1.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
}
catch(Exception e)
{
e.printStackTrace();
}
runOnUiThread( new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
imageView.setImageBitmap(myBitmap);
}
});
}
}).start();
setaswallpaper.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(myBitmap);
Toast.makeText(getApplicationContext(), "Wallpaper has been set...!!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
download.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
saveImageToSD();
// Toast.makeText(getApplicationContext(), "Wallpaper has been Downloaded...!!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
reportissue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Report Issue");
intent.putExtra(Intent.EXTRA_TEXT, "Body of email");
intent.setData(Uri.parse("mailto:reportissue#gmail.com")); // or just "mailto:" for blank
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
startActivity(intent);
}
});
}
private void saveImageToSD() {
/*--- this method will save your downloaded image to SD card ---*/
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
/*--- you can select your preferred CompressFormat and quality.
* I'm going to use JPEG and 100% quality ---*/
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
/*--- create a new file on SD card ---*/
long current = System.currentTimeMillis();
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + (current / 1000) + "wallpaper.jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/*--- create a new FileOutputStream and write bytes to file ---*/
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes.toByteArray());
fos.close();
Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want to create file in internal memory of android.
then i have to attach it to email.
please help me.
I dont know where this file is stored.???
Read through http://developer.android.com/guide/topics/data/data-storage.html and if you still have questions, post something more specific.
Its easy and try / follow this, i hope it will help you
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSend = (Button) findViewById(R.id.buttonSend);
textTo = (EditText) findViewById(R.id.editTextTo);
textSubject = (EditText) findViewById(R.id.editTextSubject);
textMessage = (EditText) findViewById(R.id.editTextMessage);
buttonSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String to = textTo.getText().toString();
String subject = textSubject.getText().toString();
String message = textMessage.getText().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text");
File data = null;
try {
Date dateVal = new Date();
String filename = dateVal.toString();
data = File.createTempFile("Report", ".csv");
FileWriter out = (FileWriter) GenerateCsv.generateCsvFile(
data, "Name,Data1");
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(data));
i.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(i, "E-mail"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public class GenerateCsv {
public static FileWriter generateCsvFile(File sFileName,String fileContent) {
FileWriter writer = null;
try {
writer = new FileWriter(sFileName);
writer.append(fileContent);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return writer;
}
}
Add this line in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-
permission>
Here is the code for Create and Read a file,
public class ReadNWriteFile extends Activity {
final String TEST_STRING = new String("Hello Android");
final String FILE_NAME = "SAMPLEFILE.txt";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
fileCreate();
tv.setText(readFile());
setContentView(tv);
}
private void fileCreate() {
try {
OutputStream os = openFileOutput(FILE_NAME, MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(os);
osw.write(TEST_STRING);
osw.close();
} catch (Exception e) {
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
private String readFile() {
try {
FileInputStream fin = openFileInput(FILE_NAME);
InputStreamReader isReader = new InputStreamReader(fin);
char[] buffer = new char[TEST_STRING.length()];
// Fill the buffer with data from file
isReader.read(buffer);
return new String(buffer);
} catch (Exception e) {
Log.i("ReadNWrite, readFile()", "Exception e = " + e);
return null;
}
}
}
To get path, /data/data/package_name/yourFile_Name
How do you implement Progress Download Dialog based on the codes below? My codes downloads images from a specific URL then it saves the image file into SD Card and set the image as wallpaper. I want to show a Progress Download Dialog when the user touches the options menu button setwallpaper().
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.set_wallpaper:
SetWallpaper(image_url);
return true;
default:
return false;
}
}
public void SetWallpaper(String image_url)
{
URL myFileUrl = null;
try
{
myFileUrl = new URL(image_url);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
Bitmap bmImg = null;
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
//int length = conn.getContentLength();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/Wallpaper/");
dir.mkdirs();
String fileName = idStr;
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
WallpaperManager wpm = WallpaperManager.getInstance(getBaseContext());
wpm.setBitmap(bmImg);
}
catch (Exception e){
e.printStackTrace();
}
}
My attempt : Caught Exception . Please refer below codes
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_THUMB_URL = "thumb_url";
ProgressBar progressbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
ImageView image = (ImageView) findViewById(R.id.single_image);
Intent in = getIntent();
String image_url = in.getStringExtra(KEY_THUMB_URL);
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
imgLoader.DisplayImage(image_url, image);
String title = in.getStringExtra(KEY_TITLE);
String artist = in.getStringExtra(KEY_ARTIST);
TextView lblName = (TextView) findViewById(R.id.name_title);
TextView lblCost = (TextView) findViewById(R.id.name_artist);
progressbar = (ProgressBar) findViewById(R.id.loadingBar);
lblName.setText(title);
lblCost.setText(artist);
}
public class loadImageTask extends AsyncTask<String, Void, Void>
{
//Drawable imgLoad;
URL myFileUrl = null;
Bitmap bmImg = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Intent in = getIntent();
String image_url = in.getStringExtra(KEY_THUMB_URL);
try {
myFileUrl = new URL(image_url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/Wallpaper/");
dir.mkdirs();
String fileName = idStr;
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(progressbar.isShown())
{
progressbar.setVisibility(View.GONE);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent in = getIntent();
String image_url = in.getStringExtra(KEY_THUMB_URL);
switch (item.getItemId()) {
case R.id.save_image:
new loadImageTask().execute(image_url);
return true;
default:
return false;
}
Here you can use the AsyncTask for the show the progressbar/dialogbox .
Show the progress bar visible inside the onPreExecute() method. And performs the image loading operations inside the doInBackground() method. Once this operation is done, we will make progress bar invisible and make imageview visible with that loaded image inside the onPostExecute() method.
For more information check this LINK
Try using this
final ProgressDialog dialog = ProgressDialog.show(
YourACtivity.this, "", "Loading...please wait");
new Thread(new Runnable() {
#Override
public void run() {
SetWallpaper(image_url);
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}).start();
}
instead of
SetWallpaper(image_url);
in the onOptionsItemSelected(MenuItem item)
and next use Handlers to handle http://developer.android.com/reference/android/os/Handler.html
I need my android app to make request to url to download an image from this url
so I have built this class to help me, BUT it didn't work ???
public class MyAsnyc extends AsyncTask<Void, Void, Void> {
public static File file;
InputStream is;
protected void doInBackground() throws IOException {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try{
// Make sure the Pictures directory exists.
path.mkdirs();
URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
// Open a connection to that URL.
URLConnection ucon = url.openConnection();
// Define InputStreams to read from the URLConnection.
is = ucon.getInputStream();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
#Override
protected Void doInBackground(Void... params) {
try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
try {
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(
null,
new String[] { file.toString() },
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
}
);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And I have, in the Activity class on onclick(), this function:
public void down(View v) {
// ImageManager ob=new ImageManager();
// ob.DownloadFromUrl("");
new MyAsnyc().execute();
}
Although I have written the permissions in the manfiest.xml
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
try this
public class MyAsnyc extends AsyncTask<Void, Void, Void> {
public static File file;
InputStream is;
protected void doInBackground() throws IOException {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try {
// Make sure the Pictures directory exists.
path.mkdirs();
URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
is = ucon.getInputStream();
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
try {
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(null,
new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Define these on the top side
Button BtnDownload;
DownloadManager downloadManager;
After, You should write on create inside :
BtnDownload = (Button)findViewById(R.id.button1);
Later, You should write to the button's click event
downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("your url");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
Finally, you need to add this onto the application tag to the manifest.xml :
<uses-permission android:name="android.permission.INTERNET"/>
new DownloadImageFromUrlTask().execute(imagePath);
//add glide dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'
public class DownloadImageFromUrlTask extends AsyncTask<String, Void, Bitmap> {
String downloadPath = "";
#Override
protected Bitmap doInBackground(String... args) {
try {
downloadPath = args[0];
return BitmapFactory.decodeStream((InputStream) new URL(downloadPath).getContent());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
String photoFileName = downloadPath.substring(downloadPath.lastIndexOf('/') + 1);
String root_Path = Environment.getExternalStorageDirectory().toString();
String saveImagePath = root_Path + "/" + photoFileName;
saveBitmapToJPEGFile(MainActivity.this, bitmap, new File(saveImagePath), 900);
loadImageWithGlide(MainActivity.this, myImageView, saveImagePath);
} else {
myImageView.setImageResource(R.drawable.default_photo);
}
}
}
public static Boolean saveBitmapToJPEGFile(Context ctx, Bitmap theTempBitmap, File theTargetFile, int i) {
Boolean result = true;
if (theTempBitmap != null) {
FileOutputStream out = null;
try {
out = new FileOutputStream(theTargetFile);
theTempBitmap.compress(Bitmap.CompressFormat.JPEG, CommonUtils.JPEG_COMPRESION_RATIO_DEFAULT, out); //kdfsJpegCompressionRatio
} catch (FileNotFoundException e) {
result = false;
e.printStackTrace();
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
result = false;
}
return result;
}
public static void loadImageWithGlide(Context theCtx, ImageView theImageView, String theUrl) {
Glide.with(theCtx)
.load(theUrl)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(theImageView);
}
The problem with your code is you have not read the InputStream.
You should try this
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
and make the Asynctask return type as Bitmap.
Or,
As you have used that is in postExecute() your doInBackground() should return that InputStream object is. But you are returning void.
Okey.Try this edited Asynctask.
private class MyAsnyc extends AsyncTask <Void,Void,File> {
File file;
#Override
protected File doInBackground( Void... params ) {
InputStream is = null;
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File( path , "Demo Picture.jpg" ) ;
try { // Make sure the Pictures directory exists.path.mkdirs() ; URL url = new URL ( "http: / /androidsaveitem .appspot.com/download.jpg") ; URLConnection ucon = url.openConnection ( ) ;
path.mkdirs();
OutputStream os = new FileOutputStream(file) ;
byte [ ] data = new byte [ is.available ( ) ] ;
is.read ( data ) ; os.write (data );is.close ( ) ; os.close ( ) ;
return file;
}
catch (Exception e){
Log .d ( "ImageManager " , " Error: " + e ) ;
}
return null;
}
protected void onPostExecute (File file) {
try{
MediaScannerConnection.scanFile( null , new String [] {file.toString( ) } , null , new MediaScannerConnection.OnScanCompletedListener ( ) { public void onScanCompleted (String path, Uri uri) {
Log.i ( " External Storage" , " Scanned " + path + " : " ) ; Log.i ( " E x t e r n a l S t o r a g e " , " - > u r i = " + uri ) ; } } ) ;
}catch (Exception e) {
// TODO: handle exception
}
}}