Java 从服务器获取图像时出错
这是我的主要活动课。我是android开发的新手,我被困在这里。从服务器获取图像时出现问题 我有一个图像加载器类,可以在imageView、内存缓存和UTIL等中加载图像Java 从服务器获取图像时出错,java,android,Java,Android,这是我的主要活动课。我是android开发的新手,我被困在这里。从服务器获取图像时出现问题 我有一个图像加载器类,可以在imageView、内存缓存和UTIL等中加载图像 public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
ListView list;
SearchView mSearchView;
LazyAdapter adapter;
JSONArray jarray;
String data = "", line = null, strresponse, txt, myjson;
BufferedReader reader;
String dataparseurl = "https://ndroid.000webhostapp.com/Php2/getListofrestaurant.php";
public String Id;
public String SName;
public String ShortAdd;
public String imagesserver;
public String hour;
public String address;
ArrayList<HashMap<String, String>> arraylist;
private String Name[] = {"Sagar Gaire Fast Food", "Sharma and Vishnu Fast Food", "Sharma FastFood",
"Domino's Pizza", "Manohar Dairy", "Greek Food & Beyond"};
private int images[] = {R.drawable.img5, R.drawable.img6, R.drawable.img9, R.drawable.img8,
R.drawable.img7, R.drawable.img11};
private String hours[] = {"10AM TO 11PM", "8AM To 10PM", "11AM To 10:30PM", "8AM To 11PM", "8AM To 9PM", "11AM To 11PM"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
DataFromServer();
mSearchView = (SearchView) findViewById(R.id.searcview1);
list = (ListView) findViewById(R.id.lv1);
}
@Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_order) {
// Handle the order action
Intent yourorder = new Intent(MainActivity.this, YourOrder_Layout.class);
startActivity(yourorder);
finish();
} else if (id == R.id.nav_cart) {
Intent cart = new Intent(MainActivity.this, Cart_Layout.class);
startActivity(cart);
finish();
} else if (id == R.id.nav_profiledit) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void DataFromServer() {
class ServerData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String[] params) {
arraylist = new ArrayList<HashMap<String, String>>();
try {
URL url = new URL(dataparseurl);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
osw.write(data);
osw.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
while (((line = reader.readLine()) != null)) {
sb.append(line);
strresponse = sb.toString();
}
txt = strresponse;
} catch (Exception e) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "OOPs Something went wrong Check Your Connection", Toast.LENGTH_SHORT).show();
}
return txt;
}
@Override
protected void onPostExecute(String result) {
if (result == null && txt == null) {
Toast.makeText(getApplicationContext(), "can't be saved", Toast.LENGTH_SHORT).show();
} else {
myjson = result;
showlist();
}
}
}
ServerData sd = new ServerData();
sd.execute();
}
private void showlist() {
try {
JSONObject jsonObject = new JSONObject(myjson);
jarray = jsonObject.getJSONArray("result");
for (int i = 0; i < jarray.length(); i++) {
JSONObject c = jarray.getJSONObject(i);
Id = c.getString("Id");
SName = c.getString("RestName");
ShortAdd = c.getString("RestAddressshort");
imagesserver = c.getString("RestPic");
hour = c.getString("Resthours");
address = c.getString("RestAddress");
HashMap<String, String> map = new HashMap<String, String>();
map.put("ID",Id);
map.put("RestName",SName);
map.put("ShortAddres",ShortAdd);
map.put("RestPic",imagesserver);
map.put("Hour",hour);
map.put("Address",address);
arraylist.add(map);
}
Toast.makeText(getApplicationContext(), arraylist.get(0)+""+arraylist.get(1)+"",Toast.LENGTH_LONG).show();
adapter = new LazyAdapter(this,arraylist);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
mSearchView.setOnQueryTextListener(this);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent info = new Intent(MainActivity.this, Info_Layout.class);
startActivity(info);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
}
public类MainActivity扩展了AppCompatActivity
实现NavigationView.OnNavigationItemSelectedListener、SearchView.OnQueryTextListener{
列表视图列表;
搜索视图;
懒散适配器;
杰索纳雷·贾雷;
String data=“”,line=null,strresponse,txt,myjson;
缓冲读取器;
字符串dataparseurl=”https://ndroid.000webhostapp.com/Php2/getListofrestaurant.php";
公共字符串Id;
公共字符串SName;
公共字符串加短;
公共字符串图像服务器;
公共弦乐小时;
公共字符串地址;
ArrayList ArrayList;
私有字符串名称[]={“Sagar Gaire快餐”、“Sharma and Vishnu快餐”、“Sharma快餐”,
“多米诺比萨饼”、“马诺哈奶制品”、“希腊食品及其他”};
私有int-images[]={R.drawable.img5,R.drawable.img6,R.drawable.img9,R.drawable.img8,
R.drawable.img7,R.drawable.img11};
私人串小时[]={“上午10时至晚上11时”、“上午8时至晚上10时”、“上午11时至晚上10时30分”、“上午8时至晚上11时”、“上午8时至晚上9时”、“上午11时至晚上11时”};
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
FloatingActionButton fab=(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
Snackbar.make(查看“替换为您自己的操作”,Snackbar.LENGTH\u LONG)
.setAction(“Action”,null).show();
}
});
抽屉布局抽屉=(抽屉布局)findViewById(R.id.抽屉布局);
ActionBarDrawerToggle切换=新建ActionBarDrawerToggle(
这,抽屉,工具栏,R.string.navigation\u drawer\u open,R.string.navigation\u drawer\u close);
抽屉。设置抽屉定位器(开关);
toggle.syncState();
NavigationView NavigationView=(NavigationView)findViewById(R.id.nav_视图);
navigationView.setNavigationItemSelectedListener(此);
DataFromServer();
mSearchView=(SearchView)findViewById(R.id.searcview1);
list=(ListView)findViewById(R.id.lv1);
}
@凌驾
公共空间{
list.setAdapter(空);
super.ondestory();
}
@凌驾
public void onBackPressed(){
抽屉布局抽屉=(抽屉布局)findViewById(R.id.抽屉布局);
if(抽屉isDrawerOpen(重力压缩机启动)){
抽屉。关闭抽屉(重力压缩机启动);
}否则{
完成();
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
//noinspection SimplifiableIf语句
if(id==R.id.action\u设置){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
@SuppressWarnings(“StatementWithEmptyBody”)
@凌驾
公共布尔值onNavigationItemSelected(@NonNull MenuItem item){
//处理导航视图项单击此处。
int id=item.getItemId();
if(id==R.id.nav_顺序){
//处理订单操作
意向yourorder=新意向(MainActivity.this,yourorder\u Layout.class);
startActivity(您的订单);
完成();
}else if(id==R.id.nav_车){
意向车=新意向(MainActivity.this,cart\u Layout.class);
星触觉(cart);
完成();
}else if(id==R.id.nav_profiledit){
}else if(id==R.id.nav_manage){
}else if(id==R.id.nav_共享){
}else if(id==R.id.nav_send){
}
抽屉布局抽屉=(抽屉布局)findViewById(R.id.抽屉布局);
抽屉。关闭抽屉(重力压缩机启动);
返回true;
}
私有void DataFromServer(){
类ServerData扩展异步任务{
@凌驾
受保护的字符串doInBackground(字符串[]参数){
arraylist=新的arraylist();
试一试{
URL URL=新URL(dataparseurl);
URLConnection conn=url.openConnection();
连接设置输出(真);
OutputStreamWriter osw=新的OutputStreamWriter(conn.getOutputStream());
写入(数据);
osw.flush();
reader=新的BufferedReader(新的InputStreamReader(conn.getInputStream());
StringBuilder sb=新的StringBuilder();
而(((line=reader.readLine())!=null)){
某人附加(行);
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
private HashMap<String, String> resultp = new HashMap<String, String>();
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> arraylist) {
activity = a;
data = arraylist;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.listitem_1, parent,false);
resultp = data.get(position);
TextView text=(TextView)vi.findViewById(R.id.textviewitemname);
TextView texttime = (TextView) vi.findViewById(R.id.textviewitemhours);
ImageView image=(ImageView)vi.findViewById(R.id.imageviewitem);
text.setText(resultp.get("RestName"));
texttime.setText(resultp.get("Hour"));
// image.setImageResource(data[position]);
imageLoader.DisplayImage(resultp.get("RestPic"),image);
return vi;
}
}
public class ImageLoader {
private MemoryCache memoryCache=new MemoryCache();
private FileCache fileCache;
private Map<ImageView, String> imageViews= Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
private ExecutorService executorService;
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService= Executors.newFixedThreadPool(5);
}
private final int stub_id = R.drawable.image1;
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p=new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from the web
try {
Bitmap bitmap;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {e.printStackTrace();}
return null;
}
//Task for the queue
private class PhotoToLoad
{
String url;
ImageView imageView;
PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
private class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
@Override
public void run() {
if(imageViewReused(photoToLoad))
return;
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
private boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
return tag == null || !tag.equals(photoToLoad.url);
}
//Used to display bitmap in the UI thread
private class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
dependencies {
compile 'com.github.bumptech.glide:glide:3.5.2'
compile 'com.android.support:support-v4:22.0.0'
}
Glide.with(context)
.load(resultp.get("RestPic"))
.into(imageView);