安卓,AS里为什么这个map没有put方法,不应该啊

图片说明

安卓,AS里为什么这个map没有put方法,不应该啊

4个回答

逻辑代码必须在方法里执行,你写在类的声明上了。写在方法、代码块、静态代码块、构造函数里都行图片说明

qq_45164369
qq_45164369 我想也只有这回事了
10 个月之前 回复

你在onCreate 方法中写一下 HashMap map = new HashMap<>(); 不能实现map.put方法,我把你AS安装包吃它。

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    HashMap<String, String> map = new HashMap<>();
    map.put("1w","1");

}

写法是没有问题的,可能你的工具类有些异常!

方法外调用不了方法,写到方法里面

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
list 中添加map出现问题,请帮忙看看

原来数据: [{tableid=material_prop_149422948, material_prop_name=亚麻, material_prop_content=2.00, rowno=2}, {tableid=material_prop_149422948, material_prop_name=二烯类弹性纤维(橡胶), material_prop_content=2.00, rowno=1}, {tableid=material_prop_149422948, material_prop_name=再生纤维素纤维, material_prop_content=12.00, rowno=0}] 想要的效果 [material_prop_name=亚麻, material_prop_content=2.00}, {material_prop_name=二烯类弹性纤维(橡胶), material_prop_content=2.00}, {material_prop_name=再生纤维素纤维, material_prop_content=12.00}] 现在效果 [{material_prop_name=再生纤维素纤维, material_prop_content=12.00}, {material_prop_name=再生纤维素纤维, material_prop_content=12.00}, {material_prop_name=再生纤维素纤维, material_prop_content=12.00}] 代码 private static PlateItemMultiComplexField setValue(List<Map<String, String>> listMap, PlateItemMultiComplexField multicomplexField) { List<PlateItemField> list = multicomplexField.getFields(); List<jeecg.tpnec.beans.item.ComplexValue> values = new ArrayList<jeecg.tpnec.beans.item.ComplexValue>(); if (null != listMap && listMap.size() > 0) { for (Map<String, String> map : listMap) { jeecg.tpnec.beans.item.ComplexValue v = new jeecg.tpnec.beans.item.ComplexValue(); for (PlateItemField f : list) { v = setField(f, map, v); } values.add(v); } } multicomplexField.setValues(values); // // multicomplexField.setComplexValues(values); return multicomplexField; }![图片说明](https://img-ask.csdn.net/upload/201707/12/1499824842_666189.png)

安卓,查询数据时怎么什么也没有查到?

数据库创建成功了,添加数据也成功了。但在查询数据跳转到第二个Activity时是白屏, 什么也没查到,调试的结果是没有进入到while里面去执行,为什么没满足while条件, 怎么改? ![图片说明](https://img-ask.csdn.net/upload/201612/16/1481840102_551791.png) ![图片说明](https://img-ask.csdn.net/upload/201612/16/1481840116_963276.png) ![图片说明](https://img-ask.csdn.net/upload/201612/16/1481840132_440910.jpg) DatabaseHelper.java ``` package com.exampl.mysql; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.widget.Toast; public class DatabaseHelper extends SQLiteOpenHelper{ private Context mContext; public static final String CREATE_TABLE_SQL="create table dict(_id integer primary key autoincrement,word text,detail text);"; public DatabaseHelper(Context context,String name,CursorFactory factory,int version) { super(context,name,factory,version); mContext=context; } public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_SQL); Toast.makeText(mContext,"创建成功!",Toast.LENGTH_LONG).show(); } public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) { } } ``` MainActivity.java ``` package com.exampl.mysql; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener{ private Button insert=null; private Button search=null; private EditText word=null; private EditText detail=null; private EditText key=null; DatabaseHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHelper=new DatabaseHelper(this,"myDict.db3",null,1); insert=(Button)findViewById(R.id.insert); insert.setOnClickListener(this); search=(Button)findViewById(R.id.search); search.setOnClickListener(this); word=(EditText)findViewById(R.id.word); detail=(EditText)findViewById(R.id.detail); key=(EditText)findViewById(R.id.key); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.insert: String wor=word.getText().toString().trim(); String det=detail.getText().toString().trim(); insertData(dbHelper.getReadableDatabase(),wor,det); Toast.makeText(this, "添加生词成功!", Toast.LENGTH_LONG).show(); break; case R.id.search: String ke=key.getText().toString().trim(); Cursor cursor=dbHelper.getReadableDatabase().rawQuery("select*from dict where ? or ?", new String[]{"%"+ke+"%","%"+ke+"%"}); Bundle data=new Bundle(); data.putSerializable("date", converCursorToList(cursor)); Intent intent=new Intent(MainActivity.this,Result.class); intent.putExtras(data); startActivity(intent); break; default:break; } } protected ArrayList<Map<String,String>> converCursorToList(Cursor cursor) { ArrayList<Map<String,String>> result=new ArrayList<Map<String,String>>(); while (cursor.moveToNext()) { Map<String,String> map=new HashMap<String,String>(); map.put("word", cursor.getString(1)); map.put("detail", cursor.getString(2)); result.add(map); } return result; } private void insertData(SQLiteDatabase db,String word,String detail) { db.execSQL("insert into dict(word,detail) values(?,?)",new String[]{word,detail}); } @Override public void onDestroy() { super.onDestroy(); if (dbHelper!=null) dbHelper.close(); } @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(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ``` Result.java ``` package com.exampl.mysql; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class Result extends Activity { private TextView jieguo=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.line); jieguo=(TextView)findViewById(R.id.jieguo); Bundle bundle=getIntent().getExtras(); jieguo.setText(bundle.getString("date")); } } ```

代码没有报错但是程序一运行就崩溃

``` public class WareShow extends Activity { private String[] bookname = new String[]{"从你的全世界路过","59秒的转动","心理罪","肖申克的救赎","疯狂Android讲义"}; private String[] penname = new String[]{"张嘉佳","周语","雷米","斯蒂芬","李刚"}; private String[] price = new String[]{"32¥","38¥","29¥","56¥","35¥"}; private int[] imageIds = new int[]{R.drawable.bg_01, R.drawable.bg_04, R.drawable.bg_02, R.drawable.bg_05, R.drawable.bg_03}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.book); List<Map<String,Object>> listItem = new ArrayList<Map<String,Object>>(); for (int i = 0; i < bookname.length; i++) { Map<String, Object> listItem1 = new HashMap<String,Object>(); listItem1.put("book", bookname[i]); listItem1.put("pen", penname[i]); listItem1.put("money", price); listItem1.put("image", imageIds); } SimpleAdapter simpleAdapter = new SimpleAdapter(this,listItem,R.layout.book,new String[]{"book","pen","money","image"},new int[]{R.id.imageIds,R.id.tv1,R.id.tv2,R.id.tv3}); ListView listView = (ListView) findViewById(R.id.lv1); listView.setAdapter(simpleAdapter); } } ``` 这段代码没有报错但是运行时程序崩溃了

Android 自定义ViewGroup addView,视图不刷新

``` class AutoArrangeLayout(context: Context, attrs: AttributeSet?) : ViewGroup(context, attrs) { var horizontalSpacing: Int = 0 set(value) { field = value requestLayout() } var verticalSpacing: Int = 0 set(value) { field = value requestLayout() } init { val ta = context.obtainStyledAttributes(attrs, R.styleable.AutoArrangeLayout) horizontalSpacing = ta.getDimensionPixelSize(R.styleable.AutoArrangeLayout_horizontalSpacing, 20) verticalSpacing = ta.getDimensionPixelSize(R.styleable.AutoArrangeLayout_verticalSpacing, 20) ta.recycle() } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { if (changed) { (0..childCount) .asSequence() .map { getChildAt(it) } .forEach { it?.let { val get = map[it] if (get != null) { it.layout(get.x, get.y, get.x + it.measuredWidth, get.y + it.measuredHeight) } } } } } var map: HashMap<View, Point> = HashMap() override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var length = paddingLeft var rowHeight = 0 var lastLineHeight = paddingTop + verticalSpacing map.clear() (0..childCount). map { getChildAt(it) } .forEach { it?.let { measureChild(it, widthMeasureSpec, heightMeasureSpec) if (it.measuredWidth + length + horizontalSpacing + paddingLeft + paddingRight <= measuredWidth) { val point = Point() length += horizontalSpacing point.x = length point.y = lastLineHeight map.put(it, point) length += it.measuredWidth rowHeight = Math.max(it.measuredHeight, rowHeight) } else { length = horizontalSpacing + paddingLeft lastLineHeight += rowHeight + verticalSpacing val point = Point() point.x = length point.y = lastLineHeight map.put(it, point) length += it.measuredWidth rowHeight = it.measuredHeight } } } val heightMode = MeasureSpec.getMode(heightMeasureSpec) var calcHeightMeasureSpec = heightMeasureSpec if (heightMode == MeasureSpec.AT_MOST) { calcHeightMeasureSpec = MeasureSpec.makeMeasureSpec(lastLineHeight + rowHeight + verticalSpacing, MeasureSpec.EXACTLY) } super.onMeasure(widthMeasureSpec, calcHeightMeasureSpec) } } ``` 上述是自定义ViewGroup的类代码,是一个自动排列布局.<br/>测试的时候在界面上还有个btn,点击一次会调用一次该类实例的addView方法,但是发现如果addView后,在该类的高设为wrap的情况下,如果高不足以新换一行则addView添加的视图不显示,若足够新换一行,则会连同之前添加的未显示的view一次性全部显示到界面上。

老是获取到position的最后一个值

不管按哪个按钮,上一次老是获取到position的第一个值,显示"苹果",然后按照网上的解决办法改了之后,老是获取到position的最后一个值,显示"运行" ![图片说明](https://img-ask.csdn.net/upload/201705/11/1494472503_511184.png) ``` package com.example.exer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ListActivity { private static final String TAG = "MainActivity"; private List<Map<String, Object>> mdata; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); ListView mListView=getListView(); mdata = data(); mListView.setAdapter(new MyAdapter(this,mdata)); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { Log.i(TAG, (String)mdata.get(position).get("title")); Toast.makeText(MainActivity.this, (String)mdata.get(position).get("title"), 1000).show(); } }); } class MyAdapter extends BaseAdapter{ private Context context; Hodler hodler =null; private LayoutInflater minflater; private ArrayList<Map<String,Object>> datalist; public MyAdapter(Context context,List<Map<String,Object>> datalist) { this.context=context; this.minflater = LayoutInflater.from(context); this.datalist=(ArrayList<Map<String,Object>>)datalist; } @Override public int getCount() { // TODO Auto-generated method stub return datalist.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return datalist.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null){ hodler = new Hodler(); convertView= minflater.inflate(R.layout.mylist, null); hodler.img = (ImageView) convertView.findViewById(R.id.img); hodler.title = (TextView) convertView.findViewById(R.id.title); hodler.info = (TextView) convertView.findViewById(R.id.info); hodler.button = (Button) convertView.findViewById(R.id.button); convertView.setTag(hodler); }else{ hodler = (Hodler)convertView.getTag(); } hodler.img.setBackgroundResource((Integer) mdata.get(position).get("img")); hodler.title.setText((CharSequence) mdata.get(position).get("title")); hodler.info.setText((CharSequence) mdata.get(position).get("info")); //hodler.button.setTag(position); hodler.positio=position; hodler.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //showdialog((int)hodler.button.getTag()); showdialog(hodler.positio); } }); return convertView; } class Hodler { public ImageView img; public TextView title; public TextView info; public Button button; int positio;//增加一个变量记录每个item的值 } } public void showdialog(int position) { new AlertDialog.Builder(this).setTitle("提示信息").setMessage("你点击的标题是: " +(String)mdata.get(position).get("title")) .setPositiveButton("确定", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show(); setResult(RESULT_OK); finish(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } public List<Map<String, Object>> data() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("title", "苹果"); map.put("info", "apple"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "书"); map.put("info", "book"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "电脑"); map.put("info", "computer"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "对话"); map.put("info", "dialog"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "运行"); map.put("info", "run"); map.put("img", R.drawable.ic_launcher); list.add(map); return list; } @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(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ```

按钮按了有反应,可onItemClick却没执行到

![图片说明](https://img-ask.csdn.net/upload/201705/10/1494389301_214240.png) ![图片说明](https://img-ask.csdn.net/upload/201705/10/1494389320_136211.jpg) 1.按钮按了有反应,可onItemClick却没执行到 2.无论按哪个按钮,都显示"你点击的标题是:苹果" ``` package com.example.exer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ListActivity { private static final String TAG = "MainActivity"; private List<Map<String, Object>> mdata; private int positio; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); ListView mListView=getListView(); mdata = data(); mListView.setAdapter(new MyAdapter(this,mdata)); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { Log.i(TAG, (String)mdata.get(position).get("title")); Toast.makeText(MainActivity.this, (String)mdata.get(position).get("title"), 1000).show(); } }); } class MyAdapter extends BaseAdapter{ private Context context; private LayoutInflater minflater; private ArrayList<Map<String,Object>> datalist; public MyAdapter(Context context,List<Map<String,Object>> datalist) { this.context=context; this.minflater = LayoutInflater.from(context); this.datalist=(ArrayList<Map<String,Object>>)datalist; } @Override public int getCount() { // TODO Auto-generated method stub return datalist.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return datalist.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub positio=position; return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { Hodler hodler =null; if(convertView == null){ hodler = new Hodler(); convertView = minflater.inflate(R.layout.mylist, null); hodler.img = (ImageView) convertView.findViewById(R.id.img); hodler.title = (TextView) convertView.findViewById(R.id.title); hodler.info = (TextView) convertView.findViewById(R.id.info); hodler.button = (Button) convertView.findViewById(R.id.button); convertView.setTag(hodler); }else{ hodler = (Hodler) convertView.getTag(); } hodler.img.setBackgroundResource((Integer) mdata.get(position).get("img")); hodler.title.setText((CharSequence) mdata.get(position).get("title")); hodler.info.setText((CharSequence) mdata.get(position).get("info")); hodler.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showdialog(); } }); return convertView; } class Hodler { public ImageView img; public TextView title; public TextView info; public Button button; } } public void showdialog() { new AlertDialog.Builder(this).setTitle("提示信息").setMessage("你点击的标题是: " +(String)mdata.get(positio).get("title")) .setPositiveButton("确定", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "确定", 1000).show(); setResult(RESULT_OK); finish(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } public List<Map<String, Object>> data() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("title", "苹果"); map.put("info", "apple"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "书"); map.put("info", "book"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "电脑"); map.put("info", "computer"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "对话"); map.put("info", "dialog"); map.put("img", R.drawable.ic_launcher); list.add(map); map = new HashMap<String, Object>(); map.put("title", "运行"); map.put("info", "run"); map.put("img", R.drawable.ic_launcher); list.add(map); return list; } @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(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ```

关于真机运行和虚拟机运行的小问题

在一个fragment里面写了一个SwipeRefreshLayout内含listview。真机运行的时候 listview的内容不会显示,但虚拟机会显示,listview的内容原是自己电脑作为服务器的 jsp传递的,这个下拉刷新两者都能用,请问这是什么原因??怎么解决 贴上代码 package com.example.my_coffeehouse.fragment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.example.my_coffeehouse.activity.R; import com.example.my_coffeehouse.util.Constant; import com.example.my_coffeehouse.util.HttpUploadUtil; import android.annotation.SuppressLint; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.SimpleAdapter; /** * 这是订单页面 * * @author Administrator * */ public class Main_OrderFragment extends Fragment { private static final int REFRESH_COMPLETE = 0X110; private SwipeRefreshLayout mSwipeLayout; private SimpleAdapter sa; private View view; private ListView lv; private String aurl = Constant.aURL + "/order/AshowOrder.jsp"; private Map<String, String> params; // 与服务器交互的标识 private Handler handler; private String[] listArray; @SuppressLint({ "HandlerLeak", "InlinedApi" }) public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.main_item_order, container, false);// 这个就相当于你加的布局 params = new HashMap<String, String>(); params.put("parame1", "wok"); new Thread() { public void run() { // 获取服务器端传输到客户端的字符串 String msgStr = HttpUploadUtil.postWithoutFile(aurl, params); Bundle b = new Bundle(); b.putString("msg", msgStr); Message msg = new Message(); msg.setData(b); msg.what = Constant.WORKER; handler.sendMessage(msg); }// run }.start(); mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.order_swipe); mSwipeLayout.setColorScheme(android.R.color.holo_green_dark, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); mSwipeLayout.setOnRefreshListener(new OnRefreshListener() { public void onRefresh() { handler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 2000); } }); // 将子线程执行的结果,交互主线程 handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case Constant.WORKER: Bundle b = msg.getData(); String m = b.getString("msg"); // 将子线程执行结果,m,交互给主线程UI层,即listView显示。 initData(m); break; case REFRESH_COMPLETE: // mDatas.addAll(Arrays.asList("Lucene", // "Canvas","Bitmap")); // sa.notifyDataSetChanged(); mSwipeLayout.setRefreshing(false); break; default: break; } } };// handler; return view; } /** * 将jsp返回的值进行解析 * * @param msg */ private void initData(String msg) { listArray = msg.split("\\|"); final int count = listArray.length / 5;// 多少条记录 List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); for (int i = 0; i < count; i++) { map = new HashMap<String, Object>(); map.put("shop", listArray[5 * i + 1]); map.put("content", listArray[5 * i + 4]); map.put("money", listArray[5 * i + 2]); map.put("time", listArray[5 * i + 3]); map.put("transition", "已完成"); list.add(map); } lv = (ListView) view.findViewById(R.id.find_listview); sa = new SimpleAdapter(this.getActivity(), list, R.layout.find_listview_item, new String[] { "shop", "content", "money", "time", "transition" }, new int[] { R.id.find_lv_item_shop, R.id.find_lv_item_content, R.id.find_lv_item_money, R.id.find_lv_item_time, R.id.find_lv_item_transition }); lv.setAdapter(sa); } }

Android在url中发送数组作为参数

<div class="post-text" itemprop="text"> <p>I am trying to send data to an API that will accept one of it's parameters as an array. <br>In PHP it is very simple to put an array as a parameter using http_build_query() function like this:</p> <pre><code>http_build_query ( array ( 'text' =&gt; 'Hello', 'info' =&gt; array('apple', 'banana') ) ) </code></pre> <p>It would yield:</p> <pre><code>text=Hello&amp;info%5B0%5D=apple&amp;info%5B1%5D=banana </code></pre> <p>That I can later use as parameters for my URL</p> <p>Is there a way to do this concept in andriod? I'm using Volley to make the requests to the server as I will expect JSON returns.</p> </div>

怎么将for循环里的数据加到下拉框spinner里

private void parseDictionary(JsonObject dics) throws JSONException { for (Map.Entry <String, JsonElement> entryBlock : dics.entrySet()) {//block if (!entryBlock.getValue().isJsonObject()) continue; for (Map.Entry <String, JsonElement> entryField : entryBlock.getValue().getAsJsonObject().entrySet()) {//field FieldBean f = BlockManager.findField( entryBlock.getKey(), entryField.getKey() ); System.out.print( "GetKey" + entryField.getKey() ); if(f != null && entryField.getValue().isJsonObject() && entryField.getKey().equals( "模块代工厂编号" ) ) { for (Map.Entry <String, JsonElement> entryValue : entryField.getValue().getAsJsonObject().entrySet()) { f.getValues().put( entryValue.getKey(), entryValue.getValue().getAsString() ); System.out.print( entryValue.getValue().getAsString() ); // moduleSN.setText( entryValue.getValue().getAsString() ); } } } } return; } ``` //请问怎么将每一个entryValue.getValue().getAsString() 的值添加到下拉框spinner里 ```

请教一个Activity跳转到另外一个Activity失败的问题

package com.example.t; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class LoginActivity extends Activity { private EditText mAccount; private EditText mPwd; private Button mLoginButton; private View loginView; private View loginSuccessView; private TextView loginSuccessShow; private LoginDataManager mUserDataManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.loginpage); mAccount=(EditText) findViewById(R.id.login_edit_account); mPwd = (EditText) findViewById(R.id.login_edit_pwd); mLoginButton = (Button) findViewById(R.id.login_btn_login); loginView=findViewById(R.id.login_view); loginSuccessView=findViewById(R.id.login_success_view); loginSuccessShow=(TextView) findViewById(R.id.login_success_show); mLoginButton.setOnClickListener(mListener); if (mUserDataManager == null) { mUserDataManager = new LoginDataManager(this); mUserDataManager.openDataBase(); } } OnClickListener mListener = new OnClickListener() { public void onClick(View v) { int id=v.getId(); if( id==R.id.login_btn_login){ login(); } } }; public void login() { if (isUserNameAndPwdValid()) { String userName = mAccount.getText().toString().trim(); String userPwd = mPwd.getText().toString().trim(); int result=mUserDataManager.findUserByNameAndPwd(userName, userPwd); if(result==1){ //login success loginView.setVisibility(View.GONE); loginSuccessView.setVisibility(View.VISIBLE); loginSuccessShow.setText(getString(R.string.user_login_sucess, userName)); Toast.makeText(this, getString(R.string.login_sucess), Toast.LENGTH_SHORT).show(); }else if(result==0){ //login failed,user does't exist Toast.makeText(this, getString(R.string.login_fail), Toast.LENGTH_SHORT).show(); } } } public void register() { if (isUserNameAndPwdValid()) { String userName = mAccount.getText().toString().trim(); String userPwd = mPwd.getText().toString().trim(); //check if user name is already exist int count=mUserDataManager.findUserByName(userName); if(count>0){ Toast.makeText(this, getString(R.string.name_already_exist, userName), Toast.LENGTH_SHORT).show(); return ; } } } public boolean isUserNameAndPwdValid() { if (mAccount.getText().toString().trim().equals("")) { Toast.makeText(this, getString(R.string.account_empty), Toast.LENGTH_SHORT).show(); return false; } else if (mPwd.getText().toString().trim().equals("")) { Toast.makeText(this, getString(R.string.pwd_empty), Toast.LENGTH_SHORT).show(); return false; } return true; } @Override protected void onResume() { if (mUserDataManager == null) { mUserDataManager = new LoginDataManager(this); mUserDataManager.openDataBase(); } super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); } @Override protected void onPause() { if (mUserDataManager != null) { mUserDataManager.closeDataBase(); mUserDataManager = null; } super.onPause(); } } 另一个 package com.example.t; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.GridView; import android.widget.SimpleAdapter; import android.widget.AdapterView.OnItemClickListener; /** * @author Administrator * @description 首页 */ public class HomePageActivity extends Activity implements OnItemClickListener { private boolean[] isPermitted; int drawableitems[] = { R.drawable.aa,R.drawable.bb,R.drawable.cc,R.drawable.dd,R.drawable.ee,R.drawable.ff,R.drawable.gg}; String[] itemsnames = { "最热单品","时尚饰品","珠宝首饰", "品质手表","潮流眼镜","绅士配件","DIY" }; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.home); GridView gridview = (GridView) findViewById(R.id.GridView); List<Map<String, Object>> itemList = new ArrayList<Map<String, Object>>(); for (int i = 0; i < itemsnames.length; i++) { Map<String, Object> map = new HashMap<String, Object>(); map.put("ItemImage", drawableitems[i]); map.put("ItemText", itemsnames[i]); itemList.add(map); } SimpleAdapter saMenuItem = new SimpleAdapter(this, itemList, // 数据源 R.layout.homeitems, // xml实现 new String[] { "ItemImage", "ItemText" }, // 对应map的Key new int[] { R.id.ItemImage, R.id.ItemText }); // 对应R的Id // 添加Item到网格中 gridview.setAdapter(saMenuItem); gridview.setOnItemClickListener(this); //permit setting isPermitted = new boolean[saMenuItem.getCount()]; } @Override public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { System.out.println("id:" + id); System.out.println("position:" + position); // String[] itemsnames = { "最热单品","时尚饰品","珠宝首饰", "品质手表","潮流眼镜","绅士配件","DIY" }; if (position == 0) { System.out.println("最热单品"); Intent intent1 = new Intent(this, HotActivity.class); startActivity(intent1); } if (position == 1) { System.out.println("时尚饰品"); Intent intent = new Intent(this, FashionActivity.class); startActivity(intent); } if (position == 2) { System.out.println("珠宝首饰"); Intent intent = new Intent(this, JewelryActivity.class); startActivity(intent); } if (position == 3) { System.out.println("品质手表"); Intent intent = new Intent(this, WatchActivity.class); startActivity(intent); } if (position == 4) { System.out.println("潮流眼镜"); Intent intent = new Intent(this, GlassesActivity.class); startActivity(intent); } if (position == 5) { System.out.println("绅士配件"); Intent intent = new Intent(this,GentryActivity.class); startActivity(intent); } if (position == 6) { System.out.println("DIY"); Intent intent = new Intent(HomePageActivity.this,DiyActicity.class); startActivity(intent); } } } 之前可能发错了,不好意思 是不是缺少了一些代码,求补充~

安卓,创建数据库时崩溃了

DatabaseHelper.java ``` package com.exampl.mysql; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.widget.Toast; public class DatabaseHelper extends SQLiteOpenHelper{ private Context mContext; public static final String CREATE_TABLE_SQL="create table dict(_id integer primary key autoincrement,word text,detail text);"; public DatabaseHelper(Context context,String name,CursorFactory factory,int version) { super(context,name,factory,version); mContext=context; } public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_SQL); Toast.makeText(mContext,"创建成功!",Toast.LENGTH_LONG).show(); } public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) { } } ``` MainActivity.java ``` package com.exampl.mysql; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener{ private Button insert=null; private Button search=null; private EditText word=null; private EditText detail=null; private EditText key=null; DatabaseHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHelper=new DatabaseHelper(this,"myDict.db3",null,1); insert=(Button)findViewById(R.id.insert); insert.setOnClickListener(this); search=(Button)findViewById(R.id.search); search.setOnClickListener(this); word=(EditText)findViewById(R.id.word); detail=(EditText)findViewById(R.id.detail); key=(EditText)findViewById(R.id.key); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.insert: String wor=word.getText().toString().trim(); String det=detail.getText().toString().trim(); insertData(dbHelper.getReadableDatabase(),wor,det); Toast.makeText(this, "添加生词成功!", Toast.LENGTH_LONG).show(); break; case R.id.search: String ke=key.getText().toString().trim(); Cursor cursor=dbHelper.getReadableDatabase().rawQuery("select*from dict where word like? or details like?", new String[]{"%"+ke+"%","%"+ke+"%"}); Bundle data=new Bundle(); data.putSerializable("date", converCursorToList(cursor)); Intent intent=new Intent(MainActivity.this,Result.class); intent.putExtras(data); startActivity(intent); break; default:break; } } protected ArrayList<Map<String,String>> converCursorToList(Cursor cursor) { ArrayList<Map<String,String>> result=new ArrayList<Map<String,String>>(); while (cursor.moveToNext()) { Map<String,String> map=new HashMap<String,String>(); map.put("word", cursor.getString(1)); map.put("detail", cursor.getString(2)); result.add(map); } return result; } private void insertData(SQLiteDatabase db,String word,String detail) { db.execSQL("insert into dict values(null,?,?)"+new String[]{word,detail}); } @Override public void onDestroy() { super.onDestroy(); if (dbHelper!=null) dbHelper.close(); } @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(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ``` Result.java ``` package com.exampl.mysql; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class Result extends Activity { private TextView jieguo=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.line); jieguo=(TextView)findViewById(R.id.jieguo); Bundle bundle=getIntent().getExtras(); jieguo.setText(bundle.getString("date")); } } ``` ![图片说明](https://img-ask.csdn.net/upload/201612/15/1481764101_229239.jpg) ![图片说明](https://img-ask.csdn.net/upload/201612/15/1481764114_286139.png) ![图片说明](https://img-ask.csdn.net/upload/201612/15/1481764138_253207.jpg)

Android Json Parse什么都不返回

<div class="post-text" itemprop="text"> <p>I have a Json Parser Class which looks like this: public class JSONParser {</p> <pre><code>static InputStream is = null; static JSONObject jObj = null; static String json = ""; public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + " "); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { JSONArray jObj = new JSONArray(json); System.out.println(jObj.toString()); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } </code></pre> <p>}</p> <p>Near the end at the last try and catch statement I print out the jsonObject as a string I correctly get the data in the console, the json looks like this:</p> <blockquote> <p>[{"id":1,"name":"Blooper","description":"Blooper","video_url":"Blooper","platform":1100110011,"logo":"","avaible":0,"token":"","created_at":"2016-04-03 17:19:49","updated_at":"2016-04-03 17:19:49","release_at":"2016-05-08"},{"id":2,"name":"Blooper","description":"Blooper","video_url":"Blooper","platform":"11000000000","logo":"","avaible":0,"token":"","created_at":"2016-04-03 17:26:13","updated_at":"2016-04-03 17:26:13","release_at":"2016-05-08"}]</p> </blockquote> <p>I used a validator and it is fine.</p> <p>In my AllProducts activity I try to display that inside the android app.</p> <p>It looks like this:</p> <pre><code>public class AllProductsActivity extends ListActivity { // Progress Dialog private ProgressDialog pDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList&lt;HashMap&lt;String, String&gt;&gt; productsList; // url to get all products list private static String url_all_products = "http://192.168.155.27:8000/index"; // JSON Node names private static final String TAG_SUCCESS = "id"; private static final String TAG_PRODUCTS = "name"; private static final String TAG_PID = "description"; private static final String TAG_NAME = "video_url"; // products JSONArray JSONArray products = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.all_products); // Hashmap for ListView productsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); // Loading products in Background Thread new LoadAllProducts().execute(); // Get listview ListView lv = getListView(); // on seleting single product // launching Edit Product Screen lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { // getting values from selected ListItem String pid = ((TextView) view.findViewById(R.id.pid)).getText() .toString(); // Starting new intent Intent in = new Intent(getApplicationContext(), EditProductActivity.class); // sending pid to next activity in.putExtra(TAG_PID, pid); // starting new activity and expecting some response back startActivityForResult(in, 100); } }); } // Response from Edit Product Activity @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // if result code 100 if (resultCode == 100) { // if result code 100 is received // means user edited/deleted product // reload this screen again Intent intent = getIntent(); finish(); startActivity(intent); } } /** * Background Async Task to Load all product by making HTTP Request * */ class LoadAllProducts extends AsyncTask&lt;String, String, String&gt; { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(AllProductsActivity.this); pDialog.setMessage("Loading products. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * getting All products from url * */ protected String doInBackground(String... args) { // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { // Building Parameters List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); // Check your log cat for JSON reponse Log.d("All Products: ", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { // products found // Getting Array of Products products = json.getJSONArray(TAG_PRODUCTS); // looping through All Products for (int i = 0; i &lt; products.length(); i++) { JSONObject c = products.getJSONObject(i); // Storing each json item in variable String id = c.getString(TAG_PID); String name = c.getString(TAG_NAME); // creating new HashMap HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); // adding each child node to HashMap key =&gt; value map.put(TAG_PID, id); map.put(TAG_NAME, name); // adding HashList to ArrayList productsList.add(map); } } else { // no products found // Launch Add New product Activity Intent i = new Intent(getApplicationContext(), NewProductActivity.class); // Closing all previous activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); } } catch (JSONException e) { e.printStackTrace(); } } }); return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( AllProductsActivity.this, productsList, R.layout.list_item, new String[] { TAG_PID, TAG_NAME}, new int[] { R.id.pid, R.id.name }); // updating listview setListAdapter(adapter); } }); } } } </code></pre> <p>If I try to print out this json:</p> <pre><code>JSONObject json = new JSONObject(); </code></pre> <p>I get no values (null), so my view keeps being empty.</p> <p>I get follwing error message:</p> <blockquote> <p>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference at com.example.androidhive.AllProductsActivity$LoadAllProducts$1.run(AllProductsActivity.java:150)</p> </blockquote> <p>Line 150 is this :</p> <pre><code>Log.d("All Products: ", json.toString()); </code></pre> <p>Thus Android Studio tells my that </p> <blockquote> <p>jObj</p> </blockquote> <p>here, in my jsonparser:</p> <pre><code>try { JSONArray jObj = new JSONArray(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } </code></pre> <p>is never used.</p> <blockquote> <p><a href="http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/" rel="nofollow">http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/</a></p> </blockquote> <p>I am not really experienced with this so I really hope for some help, thanks.</p> </div>

程序运行后,不崩溃但一片空白

``` package com.example.leadus; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; public class SjcsActivity extends Activity { private ListView lis; private List<String> list; private MyAdapter myadapter; private List<Map<String, Object>> datalist; private ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.shijianceshi); list =new ArrayList<String>(); list.add("北京"); list.add("上海"); list.add("广州"); list.add("深圳"); adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list); //adapter设置一个下拉列表的样式 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); lis = (ListView) findViewById(R.id.listView); datalist=new ArrayList<Map<String,Object>>(); myadapter = new MyAdapter(this,datalist); lis.setAdapter(myadapter); // lis.setOnItemClickListener((AdapterView.OnItemClickListener) this); // lis.setOnScrollListener((AbsListView.OnScrollListener) this); } private List<Map<String, Object>> getData() { for (int i = 1; i <7; i++) { String[]arr={"","A","B","C","D","E","F"}; Map<String, Object> map = new HashMap<String, Object>(); map.put("listView_text1",i); map.put("listView_text2", "主"+arr[i] ); map.put("listView_spinner1",i); datalist.add(map); } return datalist; } public class MyAdapter extends BaseAdapter { private Context context; private ArrayList<Map<String,Object>> datalist; private LayoutInflater inflater; public MyAdapter(Context context,List<Map<String, Object>> datalist) { this.context=context; this.inflater=LayoutInflater.from(context); this.datalist=(ArrayList<Map<String,Object>>)datalist; } @Override public int getCount() { return datalist.size(); } @Override public Object getItem(int position) { return datalist.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; ViewHolder viewHolder = null; if (convertView == null) { view =inflater.inflate(R.layout.shijianceshi_listviewlayout, null); viewHolder = new ViewHolder(); viewHolder.tv1=(TextView)view.findViewById(R.id.listView_text1); viewHolder.tv2=(TextView)view.findViewById(R.id.listView_text2); viewHolder.spinner1= (Spinner)view.findViewById(R.id.listView_spinner1); view.setTag(viewHolder); } else { view = convertView; viewHolder=(ViewHolder)view.getTag(); } viewHolder.tv1.setVisibility(View.VISIBLE); viewHolder.tv2.setVisibility(View.VISIBLE); viewHolder.tv1.setText(String.valueOf(datalist.get(position).get("listView_text1"))); viewHolder.tv2.setText(String.valueOf(datalist.get(position).get("listView_text2"))); viewHolder.spinner1.setAdapter(adapter); return view; } public class ViewHolder { TextView tv1; TextView tv2; Spinner spinner1; //你的view中的控件 } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.sjcs, 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(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ``` ![图片说明](https://img-ask.csdn.net/upload/201704/30/1493531613_869276.jpg) ![图片说明](https://img-ask.csdn.net/upload/201704/30/1493531626_427175.jpg)

求大神帮忙解答下,学习安卓的过程中,关于SampleAdapter的问题

package com.aa.cao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import android.widget.SimpleAdapter; public class MainActivity extends Activity { private ListView listview; private SimpleAdapter simp_adapter; private List<Map<String,Object>>datalist; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listview.setAdapter(simp_adapter); simp_adapter=new SimpleAdapter(this, getData(), R.layout.item, new String[]{"pic","text"}, new int[]{R.id.pic,R.id.text}); datalist=new ArrayList<Map<String,Object>>(); } private List<Map<String,Object>> getData(){ for(int i=0;i<20;i++){ Map<String,Object>map=new HashMap<String, Object>(); map.put("pic", R.drawable.ic_launcher); map.put("text", "慕课网"+i); datalist.add(map); } return datalist; } @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(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } 不知道为什么,一运行就报错,实在找不出问题,求大神帮忙解答下,感谢!

Android单选按钮值无法存储在phpmysql中:“必填字段缺失”

<div class="post-text" itemprop="text"> <p>So i've created several editText fields in Android studio with each connected to the mysql through php (I'm using xampp btw). Now my problem is, **it returns a "Required Fields are Missing"**x after changing the <code>tbuyer</code> from editText view to a 2 RadioButton namely(<code>r_tb; r_ntb</code>) inside a RadioGroup.</p> <p>Now in order to get a string from those two, I declared a <code>String role=" ";</code> with condition using the RadioGroup:</p> <pre><code>if (radioGroup.getCheckedRadioButtonId() == r_tb.getId()) { role = "Trade Buyer"; } else if (radioGroup.getCheckedRadioButtonId() == r_ntb.getId()) { role = "Non Trade Buyer"; } </code></pre> <p>then pass it along the parameters that will be sent to hash map:</p> <pre><code>@Override protected Map&lt;String, String&gt; getParams() throws AuthFailureError { //put all parameters that will be sent to hash map Map&lt;String, String&gt; params = new HashMap&lt;&gt;(); params.put("cname", cname); //String is converted to final, because we'are using it in a class; refer to line 48-50 params.put("date", date); params.put("lname", lname); params.put("fname", fname); params.put("mi", mi); params.put("email", email); params.put("city", city); params.put("country", country); params.put("tbuyer", role); // check code; String created from radio button return params; } </code></pre> <p>then call a string request for json, so that we will know if the registration is successful or not. But as I said, it returns **Required fields are missing"</p> <p>These are my codes for <strong>Buyer_Registration_Activity.java</strong>:</p> <pre><code>import android.app.ProgressDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.smdojt.manilafame.R; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class Buyer_Registration_Activity extends AppCompatActivity implements View.OnClickListener{ private EditText editTextCompanyName, editTextDate, editTextLastName, editTextFirstName, editTextMiddleInitial , editTextCity, editTextCountry, editTextType, editTextEmail; private Button buttonRegister; private ProgressDialog progressDialog; String role = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_buyer_registration); //this.setTitle("Buyer Registration"); Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar); setSupportActionBar(myToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); myToolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp); editTextCompanyName = (EditText) findViewById(R.id.editTextCompanyName); editTextDate = (EditText) findViewById(R.id.editTextDate); editTextLastName = (EditText) findViewById(R.id.editTextLastName); editTextFirstName = (EditText) findViewById(R.id.editTextFirstName); editTextMiddleInitial = (EditText) findViewById(R.id.editTextMiddleInitial); editTextCity = (EditText) findViewById(R.id.editTextCity); editTextType = (EditText) findViewById(R.id.editTextType); editTextCountry = (EditText) findViewById(R.id.editTextCountry); editTextEmail = (EditText) findViewById(R.id.editTextEmail); buttonRegister = (Button) findViewById(R.id.buttonRegister); progressDialog = new ProgressDialog(this); buttonRegister.setOnClickListener(this); } private void registerUser(){ final String cname = editTextCompanyName.getText().toString().trim(); final String date = editTextDate.getText().toString().trim(); final String lname = editTextLastName.getText().toString().trim(); final String fname = editTextFirstName.getText().toString().trim(); final String mi = editTextMiddleInitial.getText().toString().trim(); final String email = editTextEmail.getText().toString().trim(); final String city = editTextCity.getText().toString().trim(); final String country = editTextCountry.getText().toString().trim(); final String tbuyer = editTextType.getText().toString().trim(); final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup); final RadioButton r_tb = (RadioButton) findViewById(R.id.radio_tb); final RadioButton r_ntb = (RadioButton) findViewById(R.id.radio_ntb); if (radioGroup.getCheckedRadioButtonId() == r_tb.getId()) { role = "Trade Buyer"; } else if (radioGroup.getCheckedRadioButtonId() == r_ntb.getId()) { role = "Non Trade Buyer"; } progressDialog.setMessage("Registering User..."); progressDialog.show(); StringRequest stringRequest = new StringRequest(Request.Method.POST, com.example.smdojt.manilafame.sql_demo_2.Constants.URL_REGISTER, new Response.Listener&lt;String&gt;() { @Override public void onResponse(String response) {//If there are no ERROR this method will be executed progressDialog.dismiss(); //we will get the json object try { JSONObject jsonObject = new JSONObject(response); //create json object Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error) { // Else, this method will be executed progressDialog.hide(); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }){ @Override protected Map&lt;String, String&gt; getParams() throws AuthFailureError { //put all parameters that will be sent to hash map Map&lt;String, String&gt; params = new HashMap&lt;&gt;(); params.put("cname", cname); //String is converted to final, because we'are using it in a class; refer to line 48-50 params.put("date", date); params.put("lname", lname); params.put("fname", fname); params.put("mi", mi); params.put("email", email); params.put("city", city); params.put("country", country); params.put("tbuyer", role); // check code; String created from radio button //params.put("tbuyer", tbuyer); return params; } }; //add stringRequest (Line 55) RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } @Override public void onClick(View view) { if (view==buttonRegister) { registerUser(); } } } </code></pre> <p>These are my codes for <strong>DBOperations.php</strong> (Crud operations declaration)</p> <pre><code>&lt;?php //manage all php and db operations class DbOperations { private $con; function __construct() { require_once dirname(__FILE__).'/DbConnect.php'; //import dbconnect to dboperations $db = new DbConnect(); //create db connect object $this-&gt;con = $db-&gt;connect(); } //CRUD Operations below //Create----------------------------------------------------------------------------------------------- function registerBuyer($cname, $date, $lname, $fname, $mi, $email, $country, $city, $tbuyer) { //$password = md5($password); //encrypt password $stmt = $this-&gt;con-&gt;prepare("INSERT INTO `mfmis_buyers`.`buyers` (`id`, `cname`, `date`, `lname`, `fname`, `mi`, `email`, `country`, `city`, `tbuyer`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); //statement //find actual parameters /bind param $stmt-&gt;bind_param("sssssssss", $cname, $date, $lname, $fname, $mi, $email, $country, $city, $tbuyer); //bind to query //execute query below if ($stmt-&gt;execute()) //as soon as this line is called, data will be inserted into DB { return true; } else { return false; } } //----------------------------------------------------------------------------------------------------- } ?&gt; </code></pre> <p>and these are my codes for <strong>registerBuyer.php</strong> (where all my error statements comes from including <strong>"REQUIRED FIELDS ARE MISSING"</strong>)</p> <pre><code>&lt;?php require_once '../includes/DbOperations.php'; $response = array(); if($_SERVER['REQUEST_METHOD']=='POST') { if( isset($_POST['cname']) and isset($_POST['date']) and isset($_POST['lname']) and isset($_POST['fname']) and isset($_POST['mi']) and isset($_POST['email']) and isset($_POST['country']) and isset($_POST['city']) and isset($_POST['tbuyer'])) { //operate the data further $db = new DbOperations(); if($db-&gt;registerBuyer( $_POST['cname'], $_POST['date'], $_POST['lname'], $_POST['fname'], $_POST['mi'], $_POST['email'], $_POST['country'], $_POST['city'], $_POST['tbuyer'] )) { $response['error'] = false; $response['message'] = "Buyer Registered Successfully"; } else { $response['error'] = true; $response['message'] = "Some error occured try again"; } } else { $response['error'] = true; $response['message'] = "Required fields are missing"; } } else { $response['error'] = true; $response['message'] ="Invalid request"; } echo json_encode($response); ?&gt; </code></pre> </div>

自定义listview后程序直接停止运行logcat里一点错误提示都没有是什么原因

//MainActivity.java package com.example.jkd.listview; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import android.widget.SimpleAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends ActionBarActivity { private ListView listView = null; private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); private SimpleAdapter simpleAdapter = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { listView = (ListView) super.findViewById(R.id.listView); settingAdapter(); listView.setAdapter(simpleAdapter); } private void settingAdapter() { initList(); // map中的key String from[] = new String[] { "people", "name", "introduce" }; // 模板中的组件id int to[] = new int[] { R.id.people, R.id.name, R.id.introduce }; simpleAdapter = new SimpleAdapter(this, list, R.layout.listview_item, from, to); } private void initList() { // 显示的图片资源 int[] res = new int[] { R.drawable.maaa, R.drawable.mao, R.drawable.maoa, R.drawable.maoaa, R.drawable.maoaaa, }; // 定义一个二维数组来显示姓名和简介 String string[][] = new String[][] { { "猫1", "猫1简介" }, { "猫2", "猫2简介" }, { "猫3", "猫3简介" }, { "猫4", "猫4简介" }, { "猫5", "猫5简介" }, }; //初始化list数据 for (int i = 0; i < 9; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("people", res[i]); map.put("name", string[i][0]); map.put("introduce", string[i][1]); list.add(map); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.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); } } //avtivity_main.xml <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="wrap_content" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/listView" android:layout_marginTop="17dp" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> </RelativeLayout> //listview_item.xml <?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="horizontal" > <ImageView android:id="@+id/people" android:layout_width="100dp" android:layout_height="100dp" android:layout_margin="10dp" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:text="TextView" /> <TextView android:id="@+id/introduce" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:text="TextView" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> </LinearLayout>

如何在YAML文件中将JSON数据集作为字符串传递?

<div class="post-text" itemprop="text"> <p>how can i have a key in YAML format which accepts a json data as a string? I tried to put the json data in quotes but it reads as a list of map. </p> <pre><code>test1: '[{'a':'abd','asxs': 'csd','sx':'sft'}]' test2: default </code></pre> <p>I want yaml to read 'test1' as string rather than a list of dicts/maps. how do i get it?</p> <p>I get below error:</p> <blockquote> <p>Failed while parsing request input: field "Request" field "string" can only parse list of bytes or characters, invalid element: map["a":"abd" "asxs":"csd" "sx":"sft"]</p> </blockquote> </div>

如何将图像从android上传到mysql数据库,其中数据库字段是mime类型和blob

<div class="post-text" itemprop="text"> <p><strong>Table name:</strong> <code>patronimage</code> in mysql database</p> <pre><code>borrowernumber mimetype imagefile 1 image/png [BLOB - 14.1 KiB] 2 image/png [BLOB - 35.6 KiB] </code></pre> <p>i want to insert image into this table through android </p> <p><strong>Myserver code:</strong></p> <pre><code>&lt;?php include 'connection.php'; $con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die('Unable to Connect...'); if($_SERVER['REQUEST_METHOD']=='POST'){ $borrower = "109"//$_POST['borrower']; $tempName= $_FILES['filename']['tmp_name']; $imageProperties = getimageSize($_FILES['filename']['tmp_name']); $query = "INSERT INTO `patronimage`(`borrowernumber`, `mimetype`, `imagefile`)VALUES('$borrower','{$imageProperties['mime']}', '{$tempName}')"; if(mysqli_query($con,$query)){ echo json_encode(array( "status" =&gt; "true","message" =&gt; "Successfully file added!") ); }else{ echo json_encode(array( "status" =&gt; "false","message" =&gt; "Failed!") ); } } ?&gt; </code></pre> <p>Android code: Android Code of multipart request:</p> <p><strong>MainActivity.java</strong></p> <pre><code> private void uploadImage(final Bitmap bitmap){ VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, upload_URL, new Response.Listener&lt;NetworkResponse&gt;() { @Override public void onResponse(NetworkResponse response) { Log.d("ressssssoo",new String(response.data)); rQueue.getCache().clear(); try { JSONObject jsonObject = new JSONObject(new String(response.data)); Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show(); jsonObject.toString().replace("\\\\",""); if (jsonObject.getString("status").equals("true")) { arraylist = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); JSONArray dataArray = jsonObject.getJSONArray("data"); String url = ""; for (int i = 0; i &lt; dataArray.length(); i++) { JSONObject dataobj = dataArray.getJSONObject(i); url = dataobj.optString("pathToFile"); } Picasso.get().load(url).into(imageView); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }) { /* * If you want to add more parameters with the image * you can do it here * here we have only one parameter with the image * which is tags * */ @Override protected Map&lt;String, String&gt; getParams() throws AuthFailureError { Map&lt;String, String&gt; params = new HashMap&lt;&gt;(); // params.put("tags", "ccccc"); add string parameters return params; } /* *pass files using below method * */ @Override protected Map&lt;String, DataPart&gt; getByteData() { Map&lt;String, DataPart&gt; params = new HashMap&lt;&gt;(); long imagename = System.currentTimeMillis(); params.put("filename", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap))); return params; } }; volleyMultipartRequest.setRetryPolicy(new DefaultRetryPolicy( 0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); rQueue = Volley.newRequestQueue(MainActivity.this); rQueue.add(volleyMultipartRequest); } </code></pre> <p><strong>VolleyMultipartRequest.java</strong></p> <pre><code>public class VolleyMultipartRequest extends Request&lt;NetworkResponse&gt; { private final String twoHyphens = "--"; private final String lineEnd = " "; private final String boundary = "apiclient-" + System.currentTimeMillis(); private Response.Listener&lt;NetworkResponse&gt; mListener; private Response.ErrorListener mErrorListener; private Map&lt;String, String&gt; mHeaders; public VolleyMultipartRequest(int method, String url, Response.Listener&lt;NetworkResponse&gt; listener, Response.ErrorListener errorListener) { super(method, url, errorListener); this.mListener = listener; this.mErrorListener = errorListener; } @Override public Map&lt;String, String&gt; getHeaders() throws AuthFailureError { return (mHeaders != null) ? mHeaders : super.getHeaders(); } @Override public String getBodyContentType() { return "multipart/form-data;boundary=" + boundary; } @Override public byte[] getBody() throws AuthFailureError { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); try { // populate text payload Map&lt;String, String&gt; params = getParams(); if (params != null &amp;&amp; params.size() &gt; 0) { textParse(dos, params, getParamsEncoding()); } // populate data byte payload Map&lt;String, DataPart&gt; data = getByteData(); if (data != null &amp;&amp; data.size() &gt; 0) { dataParse(dos, data); } // close multipart form data after text and file data dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); return bos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * Custom method handle data payload. * * @return Map data part label with data byte * @throws AuthFailureError */ protected Map&lt;String, DataPart&gt; getByteData() throws AuthFailureError { return null; } @Override protected Response&lt;NetworkResponse&gt; parseNetworkResponse(NetworkResponse response) { try { return Response.success( response, HttpHeaderParser.parseCacheHeaders(response)); } catch (Exception e) { return Response.error(new ParseError(e)); } } @Override protected void deliverResponse(NetworkResponse response) { mListener.onResponse(response); } @Override public void deliverError(VolleyError error) { mErrorListener.onErrorResponse(error); } /** * Parse string map into data output stream by key and value. * * @param dataOutputStream data output stream handle string parsing * @param params string inputs collection * @param encoding encode the inputs, default UTF-8 * @throws IOException */ private void textParse(DataOutputStream dataOutputStream, Map&lt;String, String&gt; params, String encoding) throws IOException { try { for (Map.Entry&lt;String, String&gt; entry : params.entrySet()) { buildTextPart(dataOutputStream, entry.getKey(), entry.getValue()); } } catch (UnsupportedEncodingException uee) { throw new RuntimeException("Encoding not supported: " + encoding, uee); } } /** * Parse data into data output stream. * * @param dataOutputStream data output stream handle file attachment * @param data loop through data * @throws IOException */ private void dataParse(DataOutputStream dataOutputStream, Map&lt;String, DataPart&gt; data) throws IOException { for (Map.Entry&lt;String, DataPart&gt; entry : data.entrySet()) { buildDataPart(dataOutputStream, entry.getValue(), entry.getKey()); } } /** * Write string data into header and data output stream. * * @param dataOutputStream data output stream handle string parsing * @param parameterName name of input * @param parameterValue value of input * @throws IOException */ private void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String parameterValue) throws IOException { dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + parameterName + "\"" + lineEnd); dataOutputStream.writeBytes(lineEnd); dataOutputStream.writeBytes(parameterValue + lineEnd); } /** * Write data file into header and data output stream. * * @param dataOutputStream data output stream handle data parsing * @param dataFile data byte as DataPart from collection * @param inputName name of data input * @throws IOException */ private void buildDataPart(DataOutputStream dataOutputStream, DataPart dataFile, String inputName) throws IOException { dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + dataFile.getFileName() + "\"" + lineEnd); if (dataFile.getType() != null &amp;&amp; !dataFile.getType().trim().isEmpty()) { dataOutputStream.writeBytes("Content-Type: " + dataFile.getType() + lineEnd); } dataOutputStream.writeBytes(lineEnd); ByteArrayInputStream fileInputStream = new ByteArrayInputStream(dataFile.getContent()); int bytesAvailable = fileInputStream.available(); int maxBufferSize = 1024 * 1024; int bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; int bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead &gt; 0) { dataOutputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } dataOutputStream.writeBytes(lineEnd); } class DataPart { private String fileName; private byte[] content; private String type; public DataPart() { } DataPart(String name, byte[] data) { fileName = name; content = data; } String getFileName() { return fileName; } byte[] getContent() { return content; } String getType() { return type; } } } </code></pre> <p>I want to insert image above mentioned database table <code>patronimage</code> as blob file.</p> <p>Thank You</p> </div>

安卓,子线程获取网络图片,发消息给主线程,主线程用图片填充listview,出错

先上logcat: ![图片说明](https://img-ask.csdn.net/upload/201603/12/1457786286_765908.png) 我的xml布局就是一个按钮,和一个listview,listview里就一个imageview,按下按钮开始从网络获取图片,然后发消息到主线程,然后listview就填充数据。xml代码就不贴了。 以下是mainactivity ``` public class MainActivity extends AppCompatActivity implements View.OnClickListener{ Button but; Bitmap bitmap; ListView listView; Bitmap mainBitmap; MainHandler mainHandler=new MainHandler(); List<Map<String,Bitmap>> list=new ArrayList<>(); Map<String,Bitmap> map; Message sendMsg; List<Bitmap> bitmapList=new ArrayList<>(); @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(); } }); but=(Button)super.findViewById(R.id.but); img=(ImageView)super.findViewById(R.id.img); listView=(ListView)super.findViewById(R.id.listview); but.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.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); } public void onClick(View v) { new Thread() { public void run() { List<String> imageList=new ArrayList<>(); imageList.add("http://i1.hdslb.com/u_user/ed5c9f35b1311b3606c29d633793690b.png"); imageList.add("http://i1.hdslb.com/u_user/cfdf3c751a554873ecf4687616e1f858.jpg"); imageList.add("http://i1.hdslb.com/u_user/1462ad43f88a4b6e8b32da2447479f23.jpg"); try { Looper.prepare(); for(int i=0;i<imageList.size();i++) { URL uri = new URL(imageList.get(i)); HttpURLConnection httpURLConnection = (HttpURLConnection) uri.openConnection(); httpURLConnection.setConnectTimeout(5000); httpURLConnection.setUseCaches(false); httpURLConnection.setDoInput(true); InputStream inputStream = httpURLConnection.getInputStream(); bitmap = BitmapFactory.decodeStream(inputStream); bitmapList.add(bitmap); } Message sendFinishMessage=Message.obtain(); sendFinishMessage.what=2; mainHandler.sendMessage(sendFinishMessage); Looper.loop(); } catch (Exception e) { Log.e("this", "获取网络图片失败" + e); } } }.start(); } class MainHandler extends Handler { public void handleMessage(Message msg) { if(msg.what ==2) { for(int i=0;i<bitmapList.size();i++) { map=new HashMap<>(); map.put("image",bitmapList.get(i)); list.add(map); } initListView(); } } } public void initListView() { SimpleAdapter simpleAdapter=new SimpleAdapter(this,list,R.layout.listview,new String[]{"image"},new int[]{R.id.imageview2}); listView.setAdapter(simpleAdapter); } } ``` 代码如上,请问是哪里出了问题?

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

这是一个门针对零基础学员学习微信小程序开发的视频教学课程。课程采用腾讯官方文档作为教程的唯一技术资料来源。杜绝网络上质量良莠不齐的资料给学员学习带来的障碍。 视频课程按照开发工具的下载、安装、使用、程序结构、视图层、逻辑层、微信小程序等几个部分组织课程,详细讲解整个小程序的开发过程

Python可以这样学(第四季:数据分析与科学计算可视化)

董付国老师系列教材《Python程序设计(第2版)》(ISBN:9787302436515)、《Python可以这样学》(ISBN:9787302456469)配套视频,在教材基础上又增加了大量内容,通过实例讲解numpy、scipy、pandas、statistics、matplotlib等标准库和扩展库用法。

组成原理课程设计(实现机器数的真值还原等功能)

实现机器数的真值还原(定点小数)、定点小数的单符号位补码加减运算、定点小数的补码乘法运算和浮点数的加减运算。

javaWeb图书馆管理系统源码mysql版本

系统介绍 图书馆管理系统主要的目的是实现图书馆的信息化管理。图书馆的主要业务就是新书的借阅和归还,因此系统最核心的功能便是实现图书的借阅和归还。此外,还需要提供图书的信息查询、读者图书借阅情况的查询等

土豆浏览器

土豆浏览器可以用来看各种搞笑、电影、电视剧视频

Java面试题大全(2020版)

发现网上很多Java面试题都没有答案,所以花了很长时间搜集整理出来了这套Java面试题大全,希望对大家有帮助哈~ 本套Java面试题大全,全的不能再全,哈哈~ 一、Java 基础 1. JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境。 JRE:Java Runtime Environ...

Java8零基础入门视频教程

这门课程基于主流的java8平台,由浅入深的详细讲解了java SE的开发技术,可以使java方向的入门学员,快速扎实的掌握java开发技术!

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

TTP229触摸代码以及触摸返回值处理

自己总结的ttp229触摸代码,触摸代码以及触摸按键处理

网络工程师小白入门--【思科CCNA、华为HCNA等网络工程师认证】

本课程适合CCNA或HCNA网络小白同志,高手请绕道,可以直接学习进价课程。通过本预科课程的学习,为学习网络工程师、思科CCNA、华为HCNA这些认证打下坚实的基础! 重要!思科认证2020年2月24日起,已启用新版认证和考试,包括题库都会更新,由于疫情原因,请关注官网和本地考点信息。题库网络上很容易下载到。

深度学习原理+项目实战+算法详解+主流框架(套餐)

深度学习系列课程从深度学习基础知识点开始讲解一步步进入神经网络的世界再到卷积和递归神经网络,详解各大经典网络架构。实战部分选择当下最火爆深度学习框架PyTorch与Tensorflow/Keras,全程实战演示框架核心使用与建模方法。项目实战部分选择计算机视觉与自然语言处理领域经典项目,从零开始详解算法原理,debug模式逐行代码解读。适合准备就业和转行的同学们加入学习! 建议按照下列课程顺序来进行学习 (1)掌握深度学习必备经典网络架构 (2)深度框架实战方法 (3)计算机视觉与自然语言处理项目实战。(按照课程排列顺序即可)

java jdk 8 帮助文档 中文 文档 chm 谷歌翻译

JDK1.8 API 中文谷歌翻译版 java帮助文档 JDK API java 帮助文档 谷歌翻译 JDK1.8 API 中文 谷歌翻译版 java帮助文档 Java最新帮助文档 本帮助文档是使用谷

Ubuntu18.04安装教程

Ubuntu18.04.1安装一、准备工作1.下载Ubuntu18.04.1 LTS2.制作U盘启动盘3.准备 Ubuntu18.04.1 的硬盘空间二、安装Ubuntu18.04.1三、安装后的一些工作1.安装输入法2.更换软件源四、双系统如何卸载Ubuntu18.04.1新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列...

快速排序---(面试碰到过好几次)

原理:    快速排序,说白了就是给基准数据找其正确索引位置的过程.    如下图所示,假设最开始的基准数据为数组第一个元素23,则首先用一个临时变量去存储基准数据,即tmp=23;然后分别从数组的两端扫描数组,设两个指示标志:low指向起始位置,high指向末尾.    首先从后半部分开始,如果扫描到的值大于基准数据就让high减1,如果发现有元素比该基准数据的值小(如上图中18&amp;lt...

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

【超实用课程内容】 本课程演示的是一套基于Java的SSM框架实现的图书管理系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的java人群。详细介绍了图书管理系统的实现,包括:环境搭建、系统业务、技术实现、项目运行、功能演示、系统扩展等,以通俗易懂的方式,手把手的带你从零开始运行本套图书管理系统,该项目附带全部源码可作为毕设使用。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/27513 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化 下载方式:电脑登录https://edu.csdn.net/course/detail/27513,点击右下方课程资料、代码、课件等打包下载

HTML期末大作业

这是我自己做的HTML期末大作业,花了很多时间,稍加修改就可以作为自己的作业了,而且也可以作为学习参考

Python数据挖掘简易入门

&nbsp; &nbsp; &nbsp; &nbsp; 本课程为Python数据挖掘方向的入门课程,课程主要以真实数据为基础,详细介绍数据挖掘入门的流程和使用Python实现pandas与numpy在数据挖掘方向的运用,并深入学习如何运用scikit-learn调用常用的数据挖掘算法解决数据挖掘问题,为进一步深入学习数据挖掘打下扎实的基础。

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

想学好JAVA必须要报两万的培训班吗? Java大神勿入 如果你: 零基础想学JAVA却不知道从何入手 看了一堆书和视频却还是连JAVA的环境都搭建不起来 囊中羞涩面对两万起的JAVA培训班不忍直视 在职没有每天大块的时间专门学习JAVA 那么恭喜你找到组织了,在这里有: 1. 一群志同道合立志学好JAVA的同学一起学习讨论JAVA 2. 灵活机动的学习时间完成特定学习任务+每日编程实战练习 3. 热心助人的助教和讲师及时帮你解决问题,不按时完成作业小心助教老师的家访哦 上一张图看看前辈的感悟: &nbsp; &nbsp; 大家一定迫不及待想知道什么是极简JAVA学习营了吧,下面就来给大家说道说道: 什么是极简JAVA学习营? 1. 针对Java小白或者初级Java学习者; 2. 利用9天时间,每天1个小时时间; 3.通过 每日作业 / 组队PK / 助教答疑 / 实战编程 / 项目答辩 / 社群讨论 / 趣味知识抢答等方式让学员爱上学习编程 , 最终实现能独立开发一个基于控制台的‘库存管理系统’ 的学习模式 极简JAVA学习营是怎么学习的? &nbsp; 如何报名? 只要购买了极简JAVA一:JAVA入门就算报名成功! &nbsp;本期为第四期极简JAVA学习营,我们来看看往期学员的学习状态: 作业看这里~ &nbsp; 助教的作业报告是不是很专业 不交作业打屁屁 助教答疑是不是很用心 &nbsp; 有奖抢答大家玩的很嗨啊 &nbsp; &nbsp; 项目答辩终于开始啦 &nbsp; 优秀者的获奖感言 &nbsp; 这是答辩项目的效果 &nbsp; &nbsp; 这么细致的服务,这么好的氛围,这样的学习效果,需要多少钱呢? 不要1999,不要199,不要99,只要9.9 是的你没听错,只要9.9以上所有就都属于你了 如果你: 1、&nbsp;想学JAVA没有基础 2、&nbsp;想学JAVA没有整块的时间 3、&nbsp;想学JAVA没有足够的预算 还等什么?赶紧报名吧,抓紧抢位,本期只招300人,错过只有等时间待定的下一期了 &nbsp; 报名请加小助手微信:eduxy-1 &nbsp; &nbsp;

C++语言基础视频教程

C++语言基础视频培训课程:本课与主讲者在大学开出的程序设计课程直接对接,准确把握知识点,注重教学视频与实践体系的结合,帮助初学者有效学习。本教程详细介绍C++语言中的封装、数据隐藏、继承、多态的实现等入门知识;主要包括类的声明、对象定义、构造函数和析构函数、运算符重载、继承和派生、多态性实现等。 课程需要有C语言程序设计的基础(可以利用本人开出的《C语言与程序设计》系列课学习)。学习者能够通过实践的方式,学会利用C++语言解决问题,具备进一步学习利用C++开发应用程序的基础。

UnityLicence

UnityLicence

软件测试2小时入门

本课程内容系统、全面、简洁、通俗易懂,通过2个多小时的介绍,让大家对软件测试有个系统的理解和认识,具备基本的软件测试理论基础。 主要内容分为5个部分: 1 软件测试概述,了解测试是什么、测试的对象、原则、流程、方法、模型;&nbsp; 2.常用的黑盒测试用例设计方法及示例演示;&nbsp; 3 常用白盒测试用例设计方法及示例演示;&nbsp; 4.自动化测试优缺点、使用范围及示例‘;&nbsp; 5.测试经验谈。

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

YOLOv3是一种基于深度学习的端到端实时目标检测方法,以速度快见长。本课程将手把手地教大家使用labelImg标注和使用YOLOv3训练自己的数据集。课程分为三个小项目:足球目标检测(单目标检测)、梅西目标检测(单目标检测)、足球和梅西同时目标检测(两目标检测)。 本课程的YOLOv3使用Darknet,在Ubuntu系统上做项目演示。包括:安装Darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 Darknet是使用C语言实现的轻型开源深度学习框架,依赖少,可移植性好,值得深入探究。 除本课程《YOLOv3目标检测实战:训练自己的数据集》外,本人推出了有关YOLOv3目标检测的系列课程,请持续关注该系列的其它课程视频,包括: 《YOLOv3目标检测实战:交通标志识别》 《YOLOv3目标检测:原理与源码解析》 《YOLOv3目标检测:网络模型改进方法》 敬请关注并选择学习!

Python数据分析师-实战系列

系列课程主要包括Python数据分析必备工具包,数据分析案例实战,核心算法实战与企业级数据分析与建模解决方案实战,建议大家按照系列课程阶段顺序进行学习。所有数据集均为企业收集的真实数据集,整体风格以实战为导向,通俗讲解Python数据分析核心技巧与实战解决方案。

YOLOv3目标检测实战系列课程

《YOLOv3目标检测实战系列课程》旨在帮助大家掌握YOLOv3目标检测的训练、原理、源码与网络模型改进方法。 本课程的YOLOv3使用原作darknet(c语言编写),在Ubuntu系统上做项目演示。 本系列课程包括三门课: (1)《YOLOv3目标检测实战:训练自己的数据集》 包括:安装darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 (2)《YOLOv3目标检测:原理与源码解析》讲解YOLOv1、YOLOv2、YOLOv3的原理、程序流程并解析各层的源码。 (3)《YOLOv3目标检测:网络模型改进方法》讲解YOLOv3的改进方法,包括改进1:不显示指定类别目标的方法 (增加功能) ;改进2:合并BN层到卷积层 (加快推理速度) ; 改进3:使用GIoU指标和损失函数 (提高检测精度) ;改进4:tiny YOLOv3 (简化网络模型)并介绍 AlexeyAB/darknet项目。

超详细MySQL安装及基本使用教程

一、下载MySQL 首先,去数据库的官网http://www.mysql.com下载MySQL。 点击进入后的首页如下:  然后点击downloads,community,选择MySQL Community Server。如下图:  滑到下面,找到Recommended Download,然后点击go to download page。如下图:  点击download进入下载页面选择No...

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

图像处理和计算机视觉的课程大家已经看过很多,但总有“听不透”,“用不了”的感觉。课程致力于创建人人都能听的懂的计算机视觉,通过生动、细腻的讲解配合实战演练,让学生真正学懂、用会。 【超实用课程内容】 课程内容分为三篇,包括视觉系统构成,图像处理基础,特征提取与描述,运动跟踪,位姿估计,三维重构等内容。课程理论与实战结合,注重教学内容的可视化和工程实践,为人工智能视觉研发及算法工程师等相关高薪职位就业打下坚实基础。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/26281 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,但是大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化 下载方式:电脑登录https://edu.csdn.net/course/detail/26281,点击右下方课程资料、代码、课件等打包下载

董付国老师Python全栈学习优惠套餐

购买套餐的朋友可以关注微信公众号“Python小屋”,上传付款截图,然后领取董老师任意图书1本。

爬取妹子图片(简单入门)

安装第三方请求库 requests 被网站禁止了访问 原因是我们是Python过来的 重新给一段 可能还是存在用不了,使用网页的 编写代码 上面注意看匹配内容 User-Agent:请求对象 AppleWebKit:请求内核 Chrome浏览器 //请求网页 import requests import re //正则表达式 就是去不规则的网页里面提取有规律的信息 headers = { 'User-Agent':'存放浏览器里面的' } response = requests.get

web网页制作期末大作业

分享思维,改变世界. web网页制作,期末大作业. 所用技术:html css javascript 分享所学所得

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

相关热词 c# cad插入影像 c#设计思想 c#正则表达式 转换 c#form复制 c#写web c# 柱形图 c# wcf 服务库 c#应用程序管理器 c#数组如何赋值给数组 c#序列化应用目的博客园
立即提问