这里我得到图像扩展,无论是jpg还是png.if jpg意味着我正在使用if检查条件。如果它是真的意味着我想调用downloadfromurl并下载图像。
现在我的问题是,如果我正在调试应用程序fileNameWithoutExtn获取值为jpg和iamge也jpg两者相等意味着我想调用它不调用的函数。
任何人都可以帮助我。
java类文件
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_events_list_view);
schedule_list = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String image = ((TextView) view.findViewById(R.id.image)).getText().toString();
//String[] str1 = image.split("/");
//imagename = str1[5].trim();
//String fileName = image.substring( image.lastIndexOf('/')+1, image.length() );
String fileNameWithoutExtn = image.substring(image.lastIndexOf('.')+1);
//String ext = FilenameUtils.getExtension("/path/to/file/foo.txt");
String image1="jpg";
if(fileNameWithoutExtn==image1){
task = (DownloadFileFromURL) new DownloadFileFromURL().execute(image);
}
}
});
// Calling async task to get json
new GetSchedule().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetSchedule extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MediaCoverage.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
schedules = jsonObj.getJSONArray(TAG_SCHEDULES);
// looping through All Schdules
for (int i = 0; i < schedules.length(); i++) {
JSONObject c = schedules.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_CONTENT);
String image = c.getString(TAG_IMAGE);
String place = c.getString(TAG_PLACE);
String datetime = c.getString(TAG_DATETIME);
// Phone node is JSON Object
// tmp hashmap for Schedule
HashMap<String, String> schedule_file = new HashMap<String, String>();
// adding each child node to HashMap key => value
schedule_file.put(TAG_ID, id);
schedule_file.put(TAG_TITLE, title);
schedule_file.put(TAG_CONTENT, content);
schedule_file.put(TAG_IMAGE, image);
schedule_file.put(TAG_PLACE, place);
schedule_file.put(TAG_DATETIME, datetime);
// adding schedule list
schedule_list.add(schedule_file);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MediaCoverage.this, schedule_list,
R.layout.news_events_list_item,
new String[] { TAG_TITLE, TAG_CONTENT, TAG_IMAGE, TAG_PLACE, TAG_DATETIME },
new int[] { R.id.title,R.id.content, R.id.image, R.id.place, R.id.datetime });
setListAdapter(adapter);
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_types:
pDialogD = new ProgressDialog(this);
pDialogD.setMessage("Downloading file. Please wait...");
pDialogD.setIndeterminate(false);
pDialogD.setMax(100);
pDialogD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//pDialogD.setCancelable(true);
pDialogD.show();
return pDialogD;
default:
return null;
}
}
public static File getSaveFilePath(String fileName) {
File dir = new File(Environment.getExternalStorageDirectory(), "Image");
dir.mkdirs();
File file = new File(dir, fileName);
return file;
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
@SuppressWarnings("deprecation")
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_types);
}
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
conn = (HttpURLConnection) url.openConnection();
conn.connect();
int lenghtOfFile = conn.getContentLength();
input = new BufferedInputStream(url.openStream(), 8192);
File SDCardRoot = Environment.getExternalStorageDirectory();
// String SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
file = new File(SDCardRoot, fileNameWithoutExtn);
FileOutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialogD.setProgress(Integer.parseInt(progress[0]));
}
@SuppressWarnings("deprecation")
protected void onPostExecute(String URL) {
dismissDialog(progress_bar_types);
final String imagePath = Environment.getExternalStorageDirectory().toString()+"/"+fileNameWithoutExtn;
//String imagePath2 = Environment.getExternalStorageDirectory().toString() + "/school_calender.pdf";
Toast.makeText(getApplicationContext(), "Download Completed :"+imagePath, Toast.LENGTH_LONG).show();
//sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
MediaScannerConnection.scanFile(MediaCoverage.this, new String[] { file.toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + imagePath + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//application/pdf
}
}
public void onBackPressed() {
if (conn != null)
{
task.cancel(true);
}
finish();
}
}
logcat错误
07-25 16:04:54.085: E/AndroidRuntime(13083): FATAL EXCEPTION: main
07-25 16:04:54.085: E/AndroidRuntime(13083): java.lang.NullPointerException
07-25 16:04:54.085: E/AndroidRuntime(13083): at com.politicalmileage.vel.MediaCoverage$DownloadFileFromURL.onPostExecute(MediaCoverage.java:289)
07-25 16:04:54.085: E/AndroidRuntime(13083): at com.politicalmileage.vel.MediaCoverage$DownloadFileFromURL.onPostExecute(MediaCoverage.java:1)
07-25 16:04:54.085: E/AndroidRuntime(13083): at android.os.AsyncTask.finish(AsyncTask.java:631)
07-25 16:04:54.085: E/AndroidRuntime(13083): at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-25 16:04:54.085: E/AndroidRuntime(13083): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
07-25 16:04:54.085: E/AndroidRuntime(13083): at android.os.Handler.dispatchMessage(Handler.java:107)
07-25 16:04:54.085: E/AndroidRuntime(13083): at android.os.Looper.loop(Looper.java:194)
07-25 16:04:54.085: E/AndroidRuntime(13083): at android.app.ActivityThread.main(ActivityThread.java:5371)
07-25 16:04:54.085: E/AndroidRuntime(13083): at java.lang.reflect.Method.invokeNative(Native Method)
07-25 16:04:54.085: E/AndroidRuntime(13083): at java.lang.reflect.Method.invoke(Method.java:525)
07-25 16:04:54.085: E/AndroidRuntime(13083): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
07-25 16:04:54.085: E/AndroidRuntime(13083): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
07-25 16:04:54.085: E/AndroidRuntime(13083): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
使用fileNameWithoutExtn.contains(image1)
代替"=="
。
if(fileNameWithoutExtn==image1){
task = (DownloadFileFromURL) new DownloadFileFromURL().execute(image);
}
<强>校正的强>
if(fileNameWithoutExtn.contains(image1)){
task = (DownloadFileFromURL) new DownloadFileFromURL().execute(image);
}
你也有String.equals或String.compareTo。
答案 1 :(得分:0)
替换此
if(fileNameWithoutExtn==image1)
通过
if(fileNameWithoutExtn.equalsIgnoreCase(image1))
// if fileNameWithoutExtn = jpg
OR
if(fileNameWithoutExtn.contains(image1))
// if fileNameWithoutExtn = something something.jpg
答案 2 :(得分:0)
String [] strTemp = image.split(“。”);
for(int i=0;i<strTemp.length;i++)
{
Log.e("data is ", "strTemp[] is "+strTemp[i]);
}
String fileNameWithoutExtn=strTemp[1];
然后使用
if(fileNameWithoutExtn.equalsIgnoreCase(image1))
{ }