获取 imageview 的 id

在一个循环语句中以编程的方式创建了一些imageViews,并分配了id。当在onClick方法中我需要获得images的id,它只返回最后一幅图像的id。如何获取点击图像的id?

for (int j = 0; j < 5; j++) {
    TableRow tr = new TableRow(this);
    imageUrl = "http://ondamove.it/English/images/users/";
    imageUrl = imageUrl + listObject.get(j).getImage();

    image = new ImageView(this);
    image.setPadding(20, 10, 0, 0);
    image.setId(j+1);
    tr.addView(image);
    try {
        new DownloadFileAsync(image, new URL(imageUrl))
                .execute(imageUrl);
        images.add(image);
        //images = new ImageView[5];
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    tr.addView(image);
    table.addView(tr, new TableLayout.LayoutParams(
        LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    image.setOnClickListener(clickImageListener);

下面是 onclicklistener

private OnClickListener clickImageListener = new OnClickListener() {
    public void onClick(View v) {
        imageId = image.getId();
        Intent fullScreenIntent = new Intent(v.getContext(),FullImageActivity.class);
        fullScreenIntent.putExtra(ProfilePageNormalUser.class.getName(),imageId);
        ProfilePageNormalUser.this.startActivity(fullScreenIntent);
    }
};

3个回答

clickImageListener 的 onClick方法中获取id应该通过参数v获取id,上面循环结束后image指向的是最后一个ImageView,获取的肯定是最后一幅图像的id。

public void onClick(View v) {
        imageId = image.getId();

应该改为:

public void onClick(View v) {
        imageId = ((ImageView)v).getId();

onClick(View v)方法中可以调用 v.getId(),这将返回点击的 View 的 id。

方法中可以调用 v.getId()

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Python+OpenCV计算机视觉

Python+OpenCV计算机视觉

android获取ImageView的宽高为什么是0?

``` public class MainActivity extends Activity { private ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv = (ImageView)findViewById(R.id.iv); System.out.println(iv.getWidth()+"------"+iv.getHeight()); } ``` ![图片说明](https://img-ask.csdn.net/upload/201510/31/1446261933_226281.png)

如何以程序的方式获取一个ImageView的高度和宽度,并且在另一个 ImageView中设置?

这我使用的代码: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/white" > <ImageView android:id="@+id/first_imageview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="5dip" android:layout_marginTop="5dip" android:src="@drawable/frame" /> <ImageView android:id="@+id/second_imageview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@id/first_imageview" android:layout_alignLeft="@id/first_imageview" android:scaleType="fitXY" /> </RelativeLayout> 现在我需要检测first_imageview的高和宽,然后把这些高和宽给second_image_view设置。如何实现这个功能?

Android 使用ImageView控件时出现错误

08-10 10:08:42.701 21576-21612/com.example.uiwidgettest E/libEGL: load_driver(/system/lib/egl/libGLES_emulation.so): dlopen failed: library "/system/lib/egl/libGLES_emulation.so" not found 请问这是什么问题啊 我觉得好像是图片资源的问题,但是不知道该怎么解决

android获取网络图片显示到imageview

``` public class MainActivity extends Activity { private EditText et; private Button btn; private ImageView iv; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et = (EditText) findViewById(R.id.et); btn = (Button) findViewById(R.id.btn); iv = (ImageView) findViewById(R.id.iv); } public void click(View v){ new Thread(){ public void run(){ try { String path = et.getText().toString().trim(); File file = new File(getCacheDir(), "test.jpeg"); URL url = new URL(path); HttpURLConnection con=(HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(5000); int code=con.getResponseCode(); if(code==200){ InputStream in=con.getInputStream(); // FileOutputStream fos=new FileOutputStream(file); // int len=0; // byte[] buffer=new byte[1024]; // while((len=in.read(buffer))!=-1){ // fos.write(buffer); // } // in.close(); // fos.close(); // final Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath()); final Bitmap bitmap=BitmapFactory.decodeStream(in); runOnUiThread(new Runnable(){ public void run() { iv.setImageBitmap(bitmap); } }); } } catch (Exception e) { } } }.start(); } } ``` 获取图片然后显示出来,现在的功能正常 后期我想把图片保持到本地,然后显示的图片就是乱码图片![图片说明](https://img-ask.csdn.net/upload/201908/22/1566466293_67007.jpg) 请问哪里出错了

为什么imageview获取会报错

#报错获取id时候R文件报错。也没报错原因,也一头雾水 ![图片说明](https://img-ask.csdn.net/upload/202006/22/1592786285_270553.png)

自定义ImageView,怎么将onDraw中canvas的内容弄到imageview

自定义了一个ImageView,重写了onDraw,在onDraw里用canvas画图,然后调用了一个缩放库。我想要的效果是缩放时我用canvas画的图与background同步缩放,但只有bg在缩放,canvas没变。有什么办法能将canvas弄到bg里吗

ANDROID Fragment中动态创建ImageView

在一个ACTIVITY (CXmain) 中包含N个Fragment.现在在其中一个Fragment中需要动态创建imageview 但是运行时却出错. 目的是在在Fragment中创建一个可以滑动显示图片的功能 利用ScrollView来实现.下面是代码: public class CtFragment extends Fragment implements OnClickListener { ...................... public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ................... layout = (LinearLayout) getActivity().findViewById(R.id.layout); for(int i = 0; i < 8; i++) { // 通过资源文件来获得指定一个Drawable对象 Drawable drawable = getResources().getDrawable(R.drawable.fmj); ImageView imageView = new ImageView(getActivity()); imageView.setImageDrawable(drawable); layout.addView(imageView); } 是不是getActivity() 这样用不正确......

使用照相机拍照,获取图片路径

在程序中我使用手机相机拍一张照片,然后把这张图片保存在手机图库里面。然后我想获取图片的路径,再保存到数据库中。如何实现呢? public void onClick(View v){ switch(v.getId()) { case R.id.btnLoadPic: //Options for the dialogue menu final CharSequence[] items = {"Camera", "Gallery"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Choose an Option"); builder.setItems(items, new DialogInterface.OnClickListener() { /** * Make onclick functionality for the options in the dialogue menu */ public void onClick(DialogInterface dialog, int item) { // Camera option if (item == 0){ PackageManager pm = getPackageManager(); if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)){ //Toast.makeText(this, "camera", Toast.LENGTH_SHORT).show(); dispatchTakePictureIntent(11); } else { Toast.makeText(null, "No camera avalible", Toast.LENGTH_SHORT).show(); } } // Gallery option this works fine private void dispatchTakePictureIntent(int actionCode) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(takePictureIntent, actionCode); //handleSmallCameraPhoto(takePictureIntent); } private void handleSmallCameraPhoto(Intent intent) { Bundle extras = intent.getExtras(); Bitmap mImageBitmap = (Bitmap) extras.get("data"); ImageView mImageView = (ImageView) this.findViewById(R.id.imagePlayer); mImageView.setImageBitmap(mImageBitmap); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { handleSmallCameraPhoto(data); } 后面的代码访问照相机,然后在 imageview 中显示图像,如何在一个字符串格式中获取图片的路径?

安卓,通过url获取图片动态生成ImageView为什么生成不了?可能是什么原因?

package com.example.zz670.mypic; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ImageView; import android.widget.LinearLayout; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new work().start(); } private class work extends Thread { InputStream inputStream = null; HttpURLConnection urlConnection = null; String response; String[] gURL = new String[10]; Bitmap bitmap; ImageView imageView; LinearLayout linearLayout; public void run() { try { URL url = new URL("http://gank.io/api/random/data/福利/1"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(5000); urlConnection.setRequestMethod("GET"); int statusCode = urlConnection.getResponseCode(); if (statusCode == 200) { inputStream = new BufferedInputStream(urlConnection.getInputStream()); response = inputStream2String(inputStream); } if (!response.isEmpty()) { try { JSONObject jsonObject1 = new JSONObject(response); // Log.e("Json", response); JSONArray jsonArray = jsonObject1.getJSONArray("results"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); //取出name String jarray1 = jsonObject.getString("url"); for (int j = 0; j < 10; j++) { gURL[j] = jarray1; Log.e("Json", jarray1.toString()); // Log.e("Json", gURL[j]); } } } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } linearLayout = (LinearLayout) findViewById(R.id.id_gallery); ImageView[] imageViews = new ImageView[10]; for (int i = 0; i < imageViews.length; i++) { imageViews[i] = imageView = new ImageView(MainActivity.this); try { Bitmap bitmap = getBitmap(gURL[i]); imageView.setImageBitmap(bitmap); linearLayout.addView(imageView); } catch (Exception e) { } } } String inputStream2String(InputStream is) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = in.readLine()) != null) { buffer.append(line); } return buffer.toString(); } private Bitmap getBitmap(String path) throws IOException { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if (conn.getResponseCode() == 200) { inputStream = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } return null; } } } ``` ```

已经从手机内获取到图片的信息,怎么把图片显示在ImageView上

![图片说明](https://img-ask.csdn.net/upload/201709/13/1505287531_853527.png) 我用的是Android studio

从 web 中获取图像的 JSON 路径并把图像显示在 ImageView 中

我获取一个 website,在json中提供一个图像的路径,我想获取这个路径并在ImageView中显示一个图像。如何从web 中获取图像的JSON 路径并把图像显示在ImageView中? 提示: `targetSdkVersion="15"` { "count": "28", "data": [ { "id": "84", "thumb": "http://mmmmm.cccc.com/data/card/thum/a1f694f5ba0df9147c02b0c0c8cb83c2.jpg", "category": "Purchase", "title": "test", "locationname": "test", "latitude": "0", "longitude": "0" } ] } Activity 中: ImageView iv = (ImageView) findViewById(R.id.imageView1); iv.setImageResource(R.drawable.photo); // 显示图像在项目中,使用JSON路径如何显示图像

imageView获取图片空指针异常

通过URL获取图片时,然后在imageView中设置,结果系统给我报出空指针异常。 请高手帮忙解决一下,谢谢。 public class DetailsActivity extends Activity { ImageView thumbnail = (ImageView) findViewById(R.id.btnThumbnail); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.detail); final Bundle extras = getIntent().getExtras(); String img = extras.getString("Thumbnail"); new DownloadImageTask((ImageView) findViewById(R.id.btnThumbnail)) .execute("http://mysite.com/images/" + img); } class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { public DownloadImageTask(ImageView bmImage) { thumbnail = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Log.e("URL",urldisplay); Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { thumbnail.setImageBitmap(result); } } }

大大们,实在不行了,关于从json的图片url获取图片添加到imageview

首先呢,附上我的代码,字符串可以获取,唯独图片获取不到,这该怎么办,大大们帮忙看看,给我点介意,我会感激不尽。 package textview.exam; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.SimpleAdapter; import com.baidu.apistore.sdk.ApiCallBack; import com.baidu.apistore.sdk.ApiStoreSDK; import com.baidu.apistore.sdk.network.Parameters; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class FragmentMainchatnews extends Fragment { private String[] title;//标题 private String[] abs;//新闻简介 private String[] url;//新闻详情地址 private String[] datatime;//新闻发布时间 private String[] img_url;//新闻缩略图 Bitmap image; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.main_chat_news, null); apiTest(view); return view; } private void apiTest(final View view) { Parameters para = new Parameters(); //para.put("keyword", "娱乐"); ApiStoreSDK.execute("http://apis.baidu.com/songshuxiansheng/news/news", ApiStoreSDK.GET, para, new ApiCallBack() { @Override public void onSuccess(int status, String responseString) { Log.i("连接状态:", "连接成功"); try { JSONObject dataJson=new JSONObject(responseString); JSONArray data=dataJson.getJSONArray("retData"); // 创建一个List集合,List集合的元素是Map List<Map<String, Object>> listItems =new ArrayList<Map<String, Object>>(); //for (int i = 0; i < 5; i++) { JSONObject info = data.getJSONObject(0); image=getBitmap("http://p1.pstatp.com/list/9831/218724483"); //Bitmap bit= BitmapFactory.decodeFile(info.getString("image_url")); //bit.compress(Bitmap.CompressFormat.JPEG, 100,stream); Map<String, Object> listItem = new HashMap<String, Object>(); listItem.put("title", info.getString("title")); listItem.put("image", image); listItem.put("abs", info.getString("abstract")); listItems.add(listItem); //} // 创建一个SimpleAdapter SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), listItems,R.layout.news_simple_item, new String[]{"image", "title", "abs"}, new int[]{R.id.image, R.id.title, R.id.abs}); ListView list = (ListView) view.findViewById(R.id.chat_news); // 为ListView设置Adapter list.setAdapter(simpleAdapter); } catch (JSONException e) { Log.i("获取到数据:",responseString); } catch (IOException e) { e.printStackTrace(); } } @Override public void onComplete() { Log.i("sdkdemo", "onComplete"); } @Override public void onError(int status, String responseString, Exception e) { Log.i("sdkdemo", "onError, status: " + status); Log.i("sdkdemo", "errMsg: " + (e == null ? "" : e.getMessage())); } }); } public Bitmap getBitmap(String path) throws IOException { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if (conn.getResponseCode() == 200) { //得到输入流 InputStream inputStream = conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } return null; } } 其次呢,我对线程不是很了解,能不能有大大给我讲解一下它的用法,就拿我这个例子来说,应该怎么写线程就能使ui不堵塞

在imageview.setBackgroundResource上的空指针

在布局上有一个imageview,名称是 footer.xml,实际上是给 listview 添加的一个 footer。我需要在 listview 的末尾动态的显示图像。我在java 文件中设置的 imageview 如下: ImageView footerimage; View footerView = getLayoutInflater().inflate(R.layout.footer, null);//This is the footer layout which i have added to the listview footerimage = (ImageView)findViewById(R.id.im); footerimage.setBackgroundResource(images[i]);//images is an integer array which has drawable resources and i value is not null. lv.addFooterView(footerView, null, false); 在上面代码中的第四行获得一个空指针异常,我也把 images[i] 改成 R.drawable.someimage,但是 NPE 还是存在的,下面是 footer Layout: <?xml version="1.0" encoding="utf-8"?> <ImageView android:id="@+id/im" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:contentDescription="@string/app_name" /> 大家给予的任何建议都非常感谢!

无法执行 ImageView imageView = new ImageView(this);

我写的瀑布流显示图片 每次执行到Log.e("error","101成功压缩图片")这句就没办法执行了,下面是我的代码 import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; public class MainActivity extends Activity implements Runnable{ private final int NUM_OF_PIC = 30; //每次请求获取的图片数量 private LinearLayout linearLayout1 = null; private LinearLayout linearLayout2 = null; private LinearLayout linearLayout3 = null; private View scrollView = null; public static int USE_LINEAR_INTERVAL = 0; public static int linearlayoutWidth; private byte[][] picBytes = new byte[NUM_OF_PIC][]; private int numOfPic = 0;//已加载的图片数量 private int index = 0; public static int requestTime = 0; private PictureArrayOfBytes picArray ; private Handler mHandler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 1: try { Log.e("error","39"); addBitmaps(); Log.e("error","41"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); linearLayout1 = (LinearLayout)findViewById(R.id.main_linearlayout1); linearLayout2 = (LinearLayout)findViewById(R.id.main_linearlayout2); linearLayout3 = (LinearLayout)findViewById(R.id.main_linearlayout3); linearlayoutWidth = (int)(getWindowManager().getDefaultDisplay().getWidth()/3); Log.e("error","creat: " + String.valueOf(linearlayoutWidth)); scrollView = findViewById(R.id.scroll); Log.e("error","61"); final Thread thread = new Thread(new MainActivity()); Log.e("error","65"); thread.start(); Log.e("error","67"); Log.e("info", "context: "+(context == null)); scrollView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN : break; case MotionEvent.ACTION_MOVE : index++; break; default : break; } if (event.getAction() == MotionEvent.ACTION_UP && index > 0) { index = 0; View view = ((ScrollView) v).getChildAt(0); if (view.getMeasuredHeight() <= v.getScrollY() + v.getHeight()) { //加载数据代码 //每次加载30张图片,一共加载5次 if (numOfPic >= NUM_OF_PIC){ numOfPic = 0; thread.start(); } } } return false; } }); Log.e("error","90"); } private void addBitmaps() throws Exception{ Log.e("error","87:开始加载图片"); for (int i = 0; i < NUM_OF_PIC; i++){ Log.e("error","将图片数据转换成bitmap"); Bitmap bitmap = BitmapFactory.decodeByteArray(picBytes[i], 0, picBytes[i].length); Log.e("error","改编图片的大小"); Bitmap bitmap2 = BitmapZoom.bitmapZoomByWidth(bitmap, 240); //压缩图片大小 Log.e("error","101成功压缩图片"); Log.e("info", "context: "+(context == null)); ImageView imageView = new ImageView(this); Log.e("error","103"); imageView.setImageBitmap(bitmap); Log.e("error","105"); //根据图片的大小,为图片挖坑 LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(bitmap2.getWidth(), bitmap2.getHeight()); //将坑和图片对象联系起来 Log.e("error","109"); imageView.setLayoutParams(layoutParams); Log.e("error","111"); //按照顺序加载图片 switch (USE_LINEAR_INTERVAL) { case 0: linearLayout1.addView(imageView); numOfPic++; break; case 1: linearLayout2.addView(imageView); numOfPic++; break; case 2: linearLayout3.addView(imageView); numOfPic++; break; default: break; } USE_LINEAR_INTERVAL++; USE_LINEAR_INTERVAL= USE_LINEAR_INTERVAL%3; } } @Override public void run() { // TODO Auto-generated method stub try { requestTime++; picArray = new PictureArrayOfBytes(requestTime); picBytes = picArray.getPicByteArray(); Message message = new Message(); message.what = 1; Log.e("error","153"); mHandler.sendMessage(message); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 下面是我的logcat中的信息: 06-07 15:08:39.146: D/dalvikvm(2418): GC_CONCURRENT freed 292K, 4% free 13039K/13511K, paused 6ms+6ms 06-07 15:08:46.238: E/error(2418): 153 06-07 15:08:46.238: E/error(2418): 39 06-07 15:08:46.238: E/error(2418): 87:开始加载图片 06-07 15:08:46.238: E/error(2418): 将图片数据转换成bitmap 06-07 15:08:46.315: D/dalvikvm(2418): GC_FOR_ALLOC freed 252K, 4% free 13084K/13575K, paused 76ms 06-07 15:08:46.315: I/dalvikvm-heap(2418): Grow heap (frag case) to 12.987MB for 160016-byte allocation 06-07 15:08:46.498: D/dalvikvm(2418): GC_FOR_ALLOC freed <1K, 4% free 13240K/13767K, paused 87ms 06-07 15:08:46.498: E/error(2418): 改编图片的大小 06-07 15:08:46.566: D/dalvikvm(2418): GC_FOR_ALLOC freed 27K, 5% free 13214K/13767K, paused 66ms 06-07 15:08:46.575: I/dalvikvm-heap(2418): Grow heap (frag case) to 13.181MB for 230416-byte allocation 06-07 15:08:46.635: D/dalvikvm(2418): GC_FOR_ALLOC freed 0K, 5% free 13439K/14023K, paused 60ms **06-07 15:08:46.645: E/error(2418): 101成功压缩图片 06-07 15:08:46.655: W/System.err(2418): java.lang.NullPointerException** 06-07 15:08:46.685: W/System.err(2418):at android.content.ContextWrapper.getResources(ContextWrapper.java:81) 06-07 15:08:46.685: W/System.err(2418): at android.view.View.<init>(View.java:2696) 06-07 15:08:46.685: W/System.err(2418): at android.widget.ImageView.<init>(ImageView.java:104) 06-07 15:08:46.685: W/System.err(2418): at com.example.mywaterfallversion2.MainActivity.addBitmaps(MainActivity.java:113) 06-07 15:08:46.685: W/System.err(2418): at com.example.mywaterfallversion2.MainActivity.access$0(MainActivity.java:101) 06-07 15:08:46.698: W/System.err(2418): at com.example.mywaterfallversion2.MainActivity$1.handleMessage(MainActivity.java:39) 06-07 15:08:46.698: W/System.err(2418): at android.os.Handler.dispatchMessage(Handler.java:99) 06-07 15:08:46.698: W/System.err(2418): at android.os.Looper.loop(Looper.java:137) 06-07 15:08:46.698: W/System.err(2418): at android.app.ActivityThread.main(ActivityThread.java:4424) 06-07 15:08:46.698: W/System.err(2418): at java.lang.reflect.Method.invokeNative(Native Method) 06-07 15:08:46.706: W/System.err(2418): at java.lang.reflect.Method.invoke(Method.java:511) 06-07 15:08:46.706: W/System.err(2418): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 06-07 15:08:46.706: W/System.err(2418): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 06-07 15:08:46.706: W/System.err(2418): at dalvik.system.NativeStart.main(Native Method)

捕捉图像,然后使用 activity 在另一个布局中显示

我想通过在 FirstActivity 中点击按钮Capture捕捉图像,然后使用SecondActivity在activity_second(layout)中显示出来。如何实现? 代码部分: FirstActivity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); Button take_photo = (Button) findViewById(R.id.btn_capture); take_photo.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivity(i); } }); } Layout activity_first > <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/btn_capture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="21dp" android:text="Capture" /> </RelativeLayout> SecondActivity > public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); ImageView view = (ImageView) findViewById(R.id.view_photo); } activity_second > <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/view_photo" android:layout_width="260dp" android:layout_height="374dp" /> </LinearLayout>

Android从Web服务器获取图像到ImageView而不是缓存副本

<div class="post-text" itemprop="text"> <p>part of my android application display image on ImageView from web server(php). the name of the image on the server has the same IMEI phone number so that the phone would recognize which image belong to it</p> <p>example Imei is 33245576544535 then the image is www.example.uploads/33245576544535.jpg</p> <p>the problem is when the image change but still the same name the phone keep getting the old cashed copy of the image.</p> <p>how to get always the image from my server and not from cash server. here is the action code and thank you in advance</p> <pre><code>package com.sunil.upload; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.telephony.TelephonyManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class see extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.look); String phoneNo; TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); phoneNo=telephonyManager.getDeviceId()+""; new DownloadImageTask((ImageView) findViewById(R.id.imageView1)) .execute("http://example.com/uploads/"+phoneNo+".jpg"); } private class DownloadImageTask extends AsyncTask&lt;String, Void, Bitmap&gt; { ImageView bmImage; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } } } </code></pre> </div>

Android如何获取动态添加控件的id

``` RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.relaGameZhaiGuoZi); imgApple2 = new ImageView(this); imgApple2.setImageResource(R.drawable.app); imgApple2.setId(110); imgApple2.setOnClickListener(this); RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp1.leftMargin=30; lp1.topMargin = 100; mainLayout.addView(imgApple2,lp1); ```

图像从Android到MySQL Blob

<div class="post-text" itemprop="text"> <p>Good day everybody! As the title say, I try to load an Image from an ImageView to MySQL. I want to save it like a Blob in MySQL.</p> <p>I have seen several questions about this but no answers in my case: I still remain stuck!</p> <p>Following is my XML ImageView:</p> <pre><code>&lt;ImageView android:id="@+id/das_photoib" android:layout_width="150dp" android:layout_height="150dp" android:maxWidth = "150dp" android:maxHeight="150dp" android:layout_gravity="center_horizontal"/&gt; </code></pre> <p>Following is my JAVA activity</p> <pre><code>rootView = inflater.inflate(R.layout.devenirassistant, container, false); photoprofil = (ImageView) rootView.findViewById(R.id.das_photoib); </code></pre> <p>In the same activity, when I want to upload the picture, I put it in a ContentValues:</p> <pre><code>ContentValues cv = new ContentValues(); Bitmap bitmap = ((BitmapDrawable)photoprofil.getDrawable()).getBitmap(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); cv.put("image", Arrays.toString(b)); </code></pre> <p>Then I call an AsyncTask which call a php file itself with the contentValues as parameter. In the php file I get the "image" data and I try to load it in the MySQL "image" row of a table "image_personne", which has been define as "BLOB". I do it like this:</p> <pre><code> if (isset($_POST['image'])){ $image = imagecreatefromstring(base64_decode($_POST['image'])); $request5 = "INSERT INTO image_personne (id_personne, isDeleted, image, isModere) VALUES ({$_POST['id']}, '0', $image, 0)"; $result5 = mysqli_query($connexion,$request5) or die(mysqli_error($connexion)); } </code></pre> <p>There are no errors out, but that doesn't load! Could you help me to debug? Thank you!</p> <hr> <p>This, is what is done now:</p> <p>Android side:</p> <pre><code>ContentValues cv = new ContentValues(); Bitmap bitmap = ((BitmapDrawable)photoprofil.getDrawable()).getBitmap(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); cv.put("image", Base64.encode(b,Base64.DEFAULT)); </code></pre> <p>Php side:</p> <pre><code>$request5 = "INSERT INTO image_personne (id_personne, isDeleted, image, isModere) VALUES (?,?,?,?)"; $image = $_POST['image']; $id = $_POST['id']; $del = '0'; $mod = '0'; $stmt = $connexion-&gt;prepare($request5); //prepare the statements $stmt-&gt;bind_param("isbi", $id, $del, $null, $mod ); //bind parameter $stmt-&gt;send_long_data(0, $image); //add blob data to statement $stmt-&gt;execute(); </code></pre> </div>

2019 Python开发者日-培训

2019 Python开发者日-培训

150讲轻松搞定Python网络爬虫

150讲轻松搞定Python网络爬虫

设计模式(JAVA语言实现)--20种设计模式附带源码

设计模式(JAVA语言实现)--20种设计模式附带源码

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

java后台+微信小程序 实现完整的点餐系统

java后台+微信小程序 实现完整的点餐系统

三个项目玩转深度学习(附1G源码)

三个项目玩转深度学习(附1G源码)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

2019 AI开发者大会

2019 AI开发者大会

玩转Linux:常用命令实例指南

玩转Linux:常用命令实例指南

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

4小时玩转微信小程序——基础入门与微信支付实战

4小时玩转微信小程序——基础入门与微信支付实战

Git 实用技巧

Git 实用技巧

Python数据清洗实战入门

Python数据清洗实战入门

使用TensorFlow+keras快速构建图像分类模型

使用TensorFlow+keras快速构建图像分类模型

实用主义学Python(小白也容易上手的Python实用案例)

实用主义学Python(小白也容易上手的Python实用案例)

程序员的算法通关课:知己知彼(第一季)

程序员的算法通关课:知己知彼(第一季)

MySQL数据库从入门到实战应用

MySQL数据库从入门到实战应用

机器学习初学者必会的案例精讲

机器学习初学者必会的案例精讲

手把手实现Java图书管理系统(附源码)

手把手实现Java图书管理系统(附源码)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

.net core快速开发框架

.net core快速开发框架

玩转Python-Python3基础入门

玩转Python-Python3基础入门

Python数据挖掘简易入门

Python数据挖掘简易入门

微信公众平台开发入门

微信公众平台开发入门

程序员的兼职技能课

程序员的兼职技能课

Windows版YOLOv4目标检测实战:训练自己的数据集

Windows版YOLOv4目标检测实战:训练自己的数据集

HoloLens2开发入门教程

HoloLens2开发入门教程

微信小程序开发实战

微信小程序开发实战

Java8零基础入门视频教程

Java8零基础入门视频教程

相关热词 c# 局部 截图 页面 c#实现简单的文件管理器 c# where c# 取文件夹路径 c# 对比 当天 c# fir 滤波器 c# 和站 队列 c# txt 去空格 c#移除其他类事件 c# 自动截屏
立即提问