如何通过单击按钮
在对话框中显示列表项的确切值在上面的图片中,我们有第一个名单为IMG_20130626_095144.jpg的列表项目和名称为IMG_20130626_095154.jpg的最后一个记录
在这里我点击了第一行的上传按钮,但在Dialog中获取最后一行值,请告诉我我在哪里丢失?
活动:
// Get File Name
fileName = strPath.substring(strPath.lastIndexOf('/')+1, strPath.length());
}
答案 0 :(得分:1)
这是您的代码检查并在我们完成后回复我
public class OldUploadActivity extends Activity {
public static final String LOG_TAG = "OldUploadActivity";
private ListView lstView;
Bundle bundle;
String keytitle;
private Handler handler = new Handler();;
List <String> ImageList;
String fileName;
// created by farrukh
String selectedFileName;
TextView txtName ;
File file;
String name;
String strPath;
String strSDPath;
final private static int DIALOG_LOGIN = 1;
EditText file_name, image_name, person_name, person_email ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploads);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
bundle = getIntent().getExtras();
keytitle = bundle.getString("KEY");
/*** Get Images from SDCard ***/
ImageList = getSD();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setAdapter(new ImageAdapter(this));
}
private List <String> getSD()
{
List <String> it = new ArrayList <String>();
String string = "/mnt/sdcard/Pictures/Images/";
File f = new File (string+ keytitle+ "/");
File[] files = f.listFiles ();
for (int i = 0; i <files.length; i++)
{
File file = files[i];
it.add (file.getPath());
}
return it;
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
context = c;
}
public int getCount() {
return ImageList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_column, null);
}
// ColImgName
txtName = (TextView) convertView.findViewById(R.id.ColImgName);
Log.d("OldUploadActivity", "txtName" + txtName);
strPath = ImageList.get(position).toString();
Log.d("OldUploadActivity", "strPath" + strPath);
name = txtName.getText().toString();
// Get File Name
fileName = strPath.substring(strPath.lastIndexOf('/')+1, strPath.length());
Log.d("OldUploadActivity", "fileName" + fileName);
file = new File(strPath);
Log.d("OldUploadActivity", "file" + file);
@SuppressWarnings("unused")
long length = file.length();
txtName.setPadding(3, 0, 0, 0);
txtName.setText(fileName);
// txtName.setText(fileName + " ("+length/1024+" KB.)");
// Image Resource
ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
imageView.getLayoutParams().height = 110;
imageView.getLayoutParams().width = 110;
imageView.setPadding(10, 10, 2, 10);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Bitmap bm = BitmapFactory.decodeFile(strPath);
imageView.setImageBitmap(bm);
// ColStatus
final TextView txtStatus = (TextView) convertView.findViewById(R.id.ColStatus);
txtStatus.setPadding(3, 0, 0, 0);
txtStatus.setText("...");
// progressBar
final ProgressBar progress = (ProgressBar) convertView.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
progress.setPadding(0, 0, 0, 0);
// btnUpload
final Button btnUpload = (Button) convertView.findViewById(R.id.btnUpload);
btnUpload.setTextColor(Color.BLACK);
btnUpload.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("deprecation")
public void onClick(View v) {
// Upload
//Created by farrukh
selectedFileName=ImageList.get(position).toString().substring(strPath.lastIndexOf('/')+1, strPath.length());
showDialog(DIALOG_LOGIN);
}
});
// btnPrint
final Button btnPrint = (Button) convertView.findViewById(R.id.btnPrint);
btnPrint.setTextColor(Color.BLACK);
btnPrint.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Print
Toast.makeText(getApplicationContext(), "Print Image via Bluetooth", Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
@Override
protected Dialog onCreateDialog(int id) {
AlertDialog dialogDetails = null;
switch (id) {
case DIALOG_LOGIN:
LayoutInflater inflater = LayoutInflater.from(this);
View dialogview = inflater.inflate(R.layout.dialog_layout, null);
AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
dialogbuilder.setTitle("Image Information");
dialogbuilder.setView(dialogview);
dialogDetails = dialogbuilder.create();
break;
}
return dialogDetails;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_LOGIN:
final AlertDialog alertDialog = (AlertDialog) dialog;
Button loginbutton = (Button) alertDialog
.findViewById(R.id.btn_login);
Button cancelbutton = (Button) alertDialog
.findViewById(R.id.btn_cancel);
file_name = (EditText) alertDialog
.findViewById(R.id.edit_file_name);
/*image_name = (EditText) alertDialog
.findViewById(R.id.edit_image_name);
person_name = (EditText) alertDialog
.findViewById(R.id.edit_person_name);
person_email = (EditText) alertDialog
.findViewById(R.id.edit_person_email);*/
file_name.setText(selectedFileName);
loginbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SaveData();
alertDialog.dismiss();
}
private boolean SaveData() {
final AlertDialog.Builder ad = new AlertDialog.Builder(OldUploadActivity.this);
ad.setTitle("Error! ");
ad.setIcon(android.R.drawable.btn_star_big_on);
ad.setPositiveButton("Close", null);
String url = "http://10.0.2.2/res/uploadImage.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sFilesName", file_name.getText().toString()));
params.add(new BasicNameValuePair("sImageName", image_name.getText().toString()));
params.add(new BasicNameValuePair("sPersonName", person_name.getText().toString()));
params.add(new BasicNameValuePair("sPersonEmail", person_email.getText().toString()));
String resultServer = getHttpPost(url,params);
Log.d("Entire string::", " " + resultServer);
/*** Default Value ***/
String strStatusID = "0";
String strError = "Cannot upload Image";
JSONObject c;
try {
c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prepare Save Data
if(strStatusID.equals("0"))
{
ad.setMessage(strError);
ad.show();
}
else
{
Toast.makeText(getApplicationContext(), "Image uploaded Successfully!", Toast.LENGTH_LONG).show();
}
return true;
}
private String getHttpPost(String url,
List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
});
cancelbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
break;
}
}
//Upload
public void startUpload(final int position) {
Runnable runnable = new Runnable() {
public void run() {
handler.post(new Runnable() {
public void run() {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
// Show ProgressBar
ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
progress.setVisibility(View.VISIBLE);
// Status
TextView status = (TextView)v.findViewById(R.id.ColStatus);
status.setText("Uploading..");
new UploadFileAsync().execute(String.valueOf(position));
}
});
}
};
new Thread(runnable).start();
}
// Async Upload
public class UploadFileAsync extends AsyncTask<String, Void, Void> {
String resServer;
int position;
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
position = Integer.parseInt(params[0]);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int resCode = 0;
String resMessage = "";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
// File Path
strSDPath = ImageList.get(position).toString();
// Upload to PHP Script
String strUrlServer = "http://10.0.2.2/res/uploadFile.php";
try {
/** Check file on SD Card ***/
File file = new File(strSDPath);
if(!file.exists())
{
resServer = "{\"StatusID\":\"0\",\"Error\":\"Please check path on SD Card\"}";
return null;
}
FileInputStream fileInputStream = new FileInputStream(new File(strSDPath));
URL url = new URL(strUrlServer);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream outputStream = new DataOutputStream(conn
.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"filUpload\";filename=\""
+ strSDPath + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Response Code and Message
resCode = conn.getResponseCode();
if(resCode == HttpURLConnection.HTTP_OK)
{
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int read = 0;
while ((read = is.read()) != -1) {
bos.write(read);
}
byte[] result = bos.toByteArray();
bos.close();
resMessage = new String(result);
}
Log.d("resCode=",Integer.toString(resCode));
Log.d("resMessage=",resMessage.toString());
fileInputStream.close();
outputStream.flush();
outputStream.close();
resServer = resMessage.toString();
} catch (Exception ex) {
// Exception handling
return null;
}
return null;
}
protected void onPostExecute(Void unused) {
statusWhenFinish(position,resServer);
}
}
// when upload finish
protected void statusWhenFinish(int position, String resServer) {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
// Show ProgressBar
ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
// Status
TextView status = (TextView)v.findViewById(R.id.ColStatus);
/*** Default Value ***/
String strStatusID = "0";
String strMessage = "Unknow Status!";
try {
JSONObject c = new JSONObject(resServer);
strStatusID = c.getString("StatusID");
strMessage = c.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prepare Status
if(strStatusID.equals("0"))
{
// When update Failed
status.setText( strMessage );
status.setTextColor(Color.RED);
// Enabled Button again
Button btnUpload = (Button) v.findViewById(R.id.btnUpload);
btnUpload.setText("Already Uploaded");
btnUpload.setTextColor(Color.RED);
btnUpload.setEnabled(true);
}
else
{
status.setText("Upload Completed.");
status.setTextColor(Color.GREEN);
}
}
答案 1 :(得分:0)
您必须为每个数据传递文件名
btnUpload.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("deprecation")
public void onClick(View v) {
// Upload
Bundle bundle = new Bundle();
bundle.putString("filename", fileName );
showDialog(DIALOG_LOGIN, bundle);
}
});
然后你必须将onPrepareDialog方法更改为以下
@Override
protected void onPrepareDialog(int id, Dialog dialog, Bundle bundle) {
super.onPrepareDialog(id, dialog, bundle);
switch(id) {
case DIALOG_LOGIN:
...
...
file_name.setText(bundle.getString("filename"));
break;
}
}