Android Studio关于数据库运行报错

图片说明
Make sure the Cursor is initialized correctly before accessing data from it.
图片说明问题应该在Cursor那里,代码没有报错,不知道怎么修改。

1个回答

在访问数据之前你没有对Cursor进行初始化工作吧

weixin_40484577
weixin_40484577 感谢!已经解决了
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
android studio连接mysql数据库报错,请问这是那里的问题?

我用android studio 连接mysql数据库,用的是从maven上下载的JDBC包。但是点击运行后它提示: AGPBI: {"kind":"error","text":"Default interface methods are only supported starting with Android N (--min-api 24): com.mysql.cj.protocol.Message com.mysql.cj.interceptors.QueryInterceptor.postProcess(com.mysql.cj.protocol.Message, com.mysql.cj.protocol.Message)","sources":[{}],"tool":"D8"} FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:mergeExtDexDebug'. > Could not resolve all files for configuration ':app:debugRuntimeClasspath'. > Failed to transform file 'mysql-connector-java-8.0.11.jar' to match attributes {artifactType=android-dex, dexing-is-debuggable=true, dexing-min-sdk=15, org.gradle.usage=java-runtime-jars} > Execution failed for DexingTransform: D:\Anzhuo-SDK\android project\app\libs\mysql-connector-java-8.0.11.jar. > Error while dexing. > Failed to transform file 'mysql-connector-java-8.0.11.jar' to match attributes {artifactType=android-dex, dexing-is-debuggable=true, dexing-min-sdk=15, org.gradle.usage=java-runtime-jars} > Execution failed for DexingTransform: D:\Anzhuo-SDK\android project\app\libs\mysql-connector-java-8.0.11.jar. > Error while dexing. * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0. Use '--warning-mode all' to show the individual deprecation warnings. See https://docs.gradle.org/5.1.1/userguide/command_line_interface.html#sec:command_line_warnings BUILD FAILED in 19s 我想问一下,这是为什么?是因为JAR的版本问题吗?

Android studio 连接数据库问题 我这样写有错吗帮我看看

package com.example.administrator.testdate; import android.os.Bundle; import android.os.StrictMode; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Statement; public class MainActivity extends AppCompatActivity { String Username="root"; //数据库用户名 String Password="12345678"; //数据库用户密码 Button button1; Button button2; EditText textView1; EditText textView2; Connection conn=null; Statement stmt=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); button1 = (Button) findViewById(R.id.button1); button2 = (Button) findViewById(R.id.button2); textView1=(EditText)findViewById(R.id.editText2); textView2=(EditText)findViewById(R.id.editText) ; StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build()); 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(); } }); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connection(); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView1.setText(""); textView2.setText(""); } }); } @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 connection() { String username = textView1.getText().toString(); String password=textView2.getText().toString(); if (username != null) { //打开数据库 try {//注册驱动程序 Class.forName("com.mysql.jdbc.Driver"); } catch (java.lang.ClassNotFoundException e) { System.err.println("Driver Error " + e.getMessage()); } //连接数据库并创建Statement 对象 String sConnStr = "jdbc:mysql://localhost/testdate?user=" + Username + "&password=" + Password + "&useUnicode=true&characterEncoding=utf8"; try { conn = DriverManager.getConnection(sConnStr); conn.setAutoCommit(true); //更新数据库 String sql = "insert into testdate(username,password) values(?,?)"; PreparedStatement sta = conn.prepareStatement(sql); sta.setString(1, username); sta.setString(2, password); sta.executeUpdate(); sta.close(); conn.close(); } catch (Exception e) { System.err.println("数据库连接错误: " + e.getMessage()); return; } } } }

androidstudio数据库报错,求大神帮忙看看

![报错](https://img-ask.csdn.net/upload/201512/02/1449024588_927118.png) ![图片说明](https://img-ask.csdn.net/upload/201512/02/1449024608_714131.png) ![图片说明](https://img-ask.csdn.net/upload/201512/02/1449024620_994167.png)

安卓数据库为什么报错?

Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.query(boolean, java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String, java.lang.String, android.os.CancellationSignal)' on a null object reference ``` Cursor cursor = db.query(true, "que", new String[]{"ID", "RESOURCES"},null, null, "RESOURCES", null, "ID", null, null); ``` 我这句话应该没有错误,为什么会有空指针呢

android studiod 从数据库读取数据失败

从数据库读取数据到listview,但是不知为什么,在没添加数据进数据库的时候,能进activity,但是一旦添加进去以后就开始报错了 DBhelper.java public class DBHelper extends SQLiteOpenHelper{ private final static String DATABASE_NAME = "demo.db"; private final static int DATABASE_VERSION = 1; private final static String TABLE_NAME = "request_list"; public final static String REQUEST_ID = "request_id"; public final static String REPORTER_NAME = "reporter_name"; public final static String S_DESCRIPTION = "s_description"; public final static String L_DESCRIPTION = "l_description"; public final static String DEPARTMENT = "department"; public final static String CATEGORY = "category"; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); Log.e("Database operations", "Database created/opened"); } @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE " + TABLE_NAME + " (" + REQUEST_ID + " INTEGER primary key autoincrement, " + "" + REPORTER_NAME + " text, " + "" + S_DESCRIPTION + " text, " + "" + L_DESCRIPTION + " text, " + "" + DEPARTMENT + " text, " + "" + CATEGORY + " text);"; db.execSQL(sql); Log.e("Database operations", "Table created/opened"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "DROP TABLE IF EXISTS " + TABLE_NAME; db.execSQL(sql); onCreate(db); } public Cursor select() { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db .query(TABLE_NAME, null, null, null, null, null, null); return cursor; } public Cursor getInformation(SQLiteDatabase db) { Cursor cursor; String[] projection = {REPORTER_NAME,S_DESCRIPTION,L_DESCRIPTION,DEPARTMENT,CATEGORY}; cursor=db.query(TABLE_NAME,projection,null,null,null,null,null,null); return cursor; } //增加操作 public long insert(String s_description,String name,String department, String category,String l_description) { SQLiteDatabase db = this.getWritableDatabase(); /* ContentValues */ ContentValues cv = new ContentValues(); cv.put(S_DESCRIPTION, s_description); cv.put(L_DESCRIPTION,l_description); cv.put(REPORTER_NAME,name); cv.put(DEPARTMENT,department); cv.put(CATEGORY,category); long row = db.insert(TABLE_NAME, null, cv); return row; } //删除操作 public void delete(int id) { SQLiteDatabase db = this.getWritableDatabase(); String where = REQUEST_ID + " = ?"; String[] whereValue ={ Integer.toString(id) }; db.delete(TABLE_NAME, where, whereValue); } //修改操作 public void update(int id, String s_description,String name,String department, String category,String l_description) { SQLiteDatabase db = this.getWritableDatabase(); String where = REQUEST_ID + " = ?"; String[] whereValue = { Integer.toString(id) }; ContentValues cv = new ContentValues(); cv.put(S_DESCRIPTION, s_description); cv.put(L_DESCRIPTION,l_description); cv.put(REPORTER_NAME,name); cv.put(DEPARTMENT,department); cv.put(CATEGORY,category); db.update(TABLE_NAME, cv, where, whereValue); } } DataListActivity.java public class DataListActivity extends ActionBarActivity { ListView listView; SQLiteDatabase sqLiteDatabase; DBHelper dbHelper; Cursor cursor; ListDataAdapter listDataAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.data_list_layout); listView = (ListView) findViewById(R.id.list_view); listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.reporter_my_request); listView.setAdapter(listDataAdapter); dbHelper = new DBHelper(getApplicationContext()); sqLiteDatabase = dbHelper.getReadableDatabase(); cursor = dbHelper.getInformation(sqLiteDatabase); if(cursor.moveToFirst()) { do { String name,title,department,category,description; name = cursor.getString(0); title= cursor.getString(1); department=cursor.getString(2); category=cursor.getString(3); description=cursor.getString(4); DataProvider dataProvider=new DataProvider(name,title,department,category,description); listDataAdapter.add(dataProvider); }while (cursor.moveToNext()); } dbHelper.close(); } } DataProvider.java public class DataProvider { private String name; private String title; private String department; private String category; private String description; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public DataProvider(String name,String title,String department,String category,String description){ this.name= name; this.title = title; this.department= department; this.category= category; this.description = description; } } ListDataAdapter.java public class ListDataAdapter extends ArrayAdapter { List list = new ArrayList(); public ListDataAdapter(Context context, int resource) { super(context, resource); } static class LayoutHandler{ TextView NAME,TITLE,DEPARTMENT,CATEGORY,DESCRIPTION; } @Override public void add(Object object) { super.add(object); list.add(object); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; LayoutHandler layoutHandler; if(row == null){ LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = layoutInflater.inflate(R.layout.reporter_my_request,parent,false); layoutHandler = new LayoutHandler(); layoutHandler.NAME = (TextView)row.findViewById(R.id.text_name); layoutHandler.TITLE = (TextView)row.findViewById(R.id.text_title); layoutHandler.DEPARTMENT = (TextView)row.findViewById(R.id.text_department); layoutHandler.CATEGORY = (TextView)row.findViewById(R.id.text_category); row.setTag(layoutHandler); } else { layoutHandler = (LayoutHandler)row.getTag(); } DataProvider dataProvider = (DataProvider)this.getItem(position); layoutHandler.NAME.setText(dataProvider.getName()); layoutHandler.TITLE.setText(dataProvider.getTitle()); layoutHandler.DEPARTMENT.setText(dataProvider.getDepartment()); layoutHandler.CATEGORY.setText(dataProvider.getCategory()); layoutHandler.DESCRIPTION.setText(dataProvider.getDescription()); return row; } }

我是学android 在studio中连接网络数据库

我刚入职三天,写注册功能,存新用户到数据库,公司PHP的哥们提供了一个网络数据库接口http://192.168.1.27/phpmyadmin/index.php,数据库名diancan, 表名members,账号和密码我也有,我怎么才能连接到这个数据库?求大神给出代码 感激不尽,不想失业

android studio运行报下列错误

1.貌似有问题的代码 package com.example.coolweather; import android.app.Fragment; import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.example.coolweather.db.City; import com.example.coolweather.db.County; import com.example.coolweather.db.Province; import com.example.coolweather.util.HttpUtil; import com.example.coolweather.util.Utility; import org.litepal.crud.DataSupport; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by Airth on 2019/5/10. */ public class ChooseAreaFragment extends Fragment { public static final int LEVEL_PROVINCE=0; public static final int LEVEL_CITY=1; public static final int LEVEL_COUNTY=2; private ProgressDialog progressDialog; private TextView titleText; private Button backButton; private ListView listView; private ArrayAdapter<String> adapter; private List<String> dataList = new ArrayList<>(); private int currentLevel; //当前被选中的级别 private Province selectedProvince;//被选中的省份 private City selectedCity;//被选中的城市 private List<Province> provinceList;//省列表 private List<City> cityList;//市列表 private List<County> countyList ;//县列表 /*获取控件实例id*/ @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { Log.d("ChooseAreaFragment","onCreateView"); View view = inflater.inflate(R.layout.choose_area,container,false); titleText = (TextView)view.findViewById(R.id.title_text); //获取标题栏文本id backButton = (Button) view.findViewById(R.id.back_button); //获取标题栏id listView = (ListView)view.findViewById(R.id.list_view); //获取Item列表id //获取ArrayAdapter对象 adapter =new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter);//设置并初始化适配器 return view;//将视图返回 } /*点击事件集合*/ @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { Log.d("ChooseAreaFragment","onActivityCreated"); super.onActivityCreated(savedInstanceState); //列表任意一栏被点击,则... listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.d("ChooseAreaFragment","列表被点了的..."); if (currentLevel == LEVEL_PROVINCE){ //当前选中的级别为省份时 selectedProvince = provinceList.get(position); //当前点击为选中状态 queryCities();//查询市的方法 } else if (currentLevel == LEVEL_CITY){ selectedCity = cityList.get(position); queryCounties(); } } }); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (currentLevel == LEVEL_COUNTY){ queryCities(); } else if (currentLevel == LEVEL_CITY){ queryProvinces(); } } }); queryProvinces(); } private void queryCities() { titleText.setText(selectedProvince.getProvinceName()); //设置市的标题内容 backButton.setVisibility(View.VISIBLE); //设置返回按钮可见 //查询被选中的省份城市的市区 cityList = DataSupport.where("provinceid=?",String.valueOf(selectedProvince. getId())).find(City.class); Log.d("ChooseAreaFragment","市级"); if (cityList.size()>0){ //如果省列表不为空,则... dataList.clear(); for (City city:cityList){ //遍历每一份省的市级城市 dataList.add(city.getCityName()); //添加到数据列表中 } adapter.notifyDataSetChanged();//通知适配器数据更新了 listView.setSelection(0); currentLevel = LEVEL_CITY; } else{ int provinceCode = selectedProvince.getProvinceCode(); //获取被选取省级代码 String address = "http://guolin.tech/api/china/"+provinceCode;//获取被选取地区的网络地址 Log.d("ChooseAreaFragment","准备在网络中获取地址信息"); queryFromServer(address,"city"); // 在网络中查询 } } /*根据传入的地址和类型从服务器查询省市县数据*/ private void queryFromServer(String adress, final String type) { showProgressDialog(); // 发送一条网络请求 HttpUtil.sendOKHttpRequest(adress, new Callback() { //请求加载失败 @Override public void onFailure(Call call, IOException e) { //通过runOnUiThread方法回到主线程逻辑 getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { Log.d("ChooseAreaFragment","加载地区信息..."); String responseText = response.body().string(); boolean result = false; if ("province".equals(type)){ result = Utility.handleProvinceResponse(responseText); } else if ("city".equals(type)){ result = Utility.handleCityResponse(responseText,selectedProvince.getId()); } else if ("county".equals(type)){ result = Utility.handleCountyResponse(responseText, selectedCity.getId()); } if (result) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { Log.d("ChooseAreaFragment","开启线程更新UI"); closeProgressDialog(); if ("province".equals(type)){ queryProvinces(); } else if ("city".equals(type)){ queryCities(); } else if ("county".equals(type)){ queryCounties(); } } }); } if ("city".equals(type)){ result = Utility.handleProvinceResponse(responseText); } if ("county".equals(type)){ result = Utility.handleProvinceResponse(responseText); } } }); } /*显示进度对话框*/ private void showProgressDialog() { if (progressDialog==null){ progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("正在加载..."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } private void queryCounties() { titleText.setText(selectedCity.getCityName()); backButton.setVisibility(View.VISIBLE); countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class); if (countyList.size()>0){ dataList.clear(); for (County county:countyList){ dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel=LEVEL_COUNTY; } else { int provinceCode = selectedProvince.getProvinceCode(); int cityCode = selectedCity.getCityCode(); String address = "http://guolin.tech/api/china/"+provinceCode+"/"+cityCode; queryFromServer(address,"county"); } } /*全国所有的省,优先查询数据库,如果没有再去服务器查询*/ private void queryProvinces() { titleText.setText("中国"); Log.d("ChooseAreaFragment","查询省中..."); backButton.setVisibility(View.GONE); provinceList = DataSupport.findAll(Province.class); if (provinceList.size()>0){ dataList.clear(); for (Province province:provinceList){ dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_PROVINCE; } else { Log.d("ChooseAreaFragment","服务器查询省中..."); String address = "http://guolin.tech/api/china"; queryFromServer(address,"province"); } } private void closeProgressDialog() { if (progressDialog!=null){ progressDialog.dismiss(); } } } 2.这是报错日志 ![图片说明](https://img-ask.csdn.net/upload/201905/10/1557481080_879893.png)

Android Studio第一次创建项目出现的问题

![图片说明](https://img-ask.csdn.net/upload/201709/22/1506062710_995700.png) MianActivity Java类中出现黄线提示 ![图片说明](https://img-ask.csdn.net/upload/201709/22/1506062830_700494.png) 无明显报错提示 ![图片说明](https://img-ask.csdn.net/upload/201709/22/1506062879_784711.png) 在布局文件activity main包括其他所有XML都有此问题 # 求问大神们有办法解决这个问题么????

【急】【Android studio】 【将Sqlite显示到listview】为什么我的listview只显示一个 item,数据库里明明有三四条数据

【Android studio】 【将Sqlite显示到listview】为什么我的listview只显示一个 item,数据库里明明有三四条数据 lv.setAdapter(new BaseAdapter() { /* * 为ListView设置一个适配器 * getCount()返回数据个数 * getView()为每一行设置一个条目 * */ @Override public int getCount() { return goodsArray.size(); } @Override public Object getItem(int position) { // return studentlist.get(position); return null; } @Override public long getItemId(int position) { // return position; return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view ; /**对ListView的优化,convertView为空时,创建一个新视图; * convertView不为空时,代表它是滚出, * 放入Recycler中的视图,若需要用到其他layout, * 则用inflate(),同一视图,用fiindViewBy() * **/ if(convertView == null ) { LayoutInflater inflater = getActivity().getLayoutInflater(); view = inflater.inflate(R.layout.item,null); // view = inflater.inflate(R.layout.item,null); //view = View.inflate(getBaseContext(),R.layout.item,null); } else { view = convertView; } //从goodsArray中取出一行数据,position相当于数组下标,可以实现逐行取数据 goodsInfo goodsinfo = goodsArray.get(position); TextView name = (TextView)view.findViewById(R.id.listview_name); TextView goods_number = (TextView)view.findViewById(R.id.listview_goodsnumber); TextView in_price = (TextView)view.findViewById(R.id.listview_inprice); TextView out_price = (TextView)view.findViewById(R.id.listview_outprice); TextView update_time = (TextView)view.findViewById(R.id.listview_updatetime); name.setText(goodsinfo.getName()); goods_number.setText(goodsinfo.getgoods_number()); in_price.setText(String.valueOf(goodsinfo.getin_price())); out_price.setText(String.valueOf(goodsinfo.getout_price())); update_time.setText(goodsinfo.getupdate_time()); return view; } });

android通过jdbc连接数据库问题

需要通过jdbc连接访问数据库,目前我是通过需要访问数据库的时候建立于数据库的连接,得到需要的结果后就断开与数据库的连接。但是由于工作需要,现在需要android应用程序在登陆界面输入账号密码后就持续连接数据库,只有当app退出后才会断开与数据库的连接,请问是否可行,该如何操作,望大神指点一二,感激不尽!

App没有在数据库中插入任何内容

<div class="post-text" itemprop="text"> <p>I am unable to find out what's wrong with the following, this is my php code:</p> <pre><code>&lt;?php include_once 'dbconnect.php'; if($_SERVER['REQUEST_METHOD']=='POST'){ $number= $_POST['number']; $name = $_POST['name']; $city = $_POST['city']; $street = $_POST['street']; $building = $_POST['building']; $email = $_POST['email']; $password = $_POST['pass']; if($number=='' || $name=='' || $city=='' || $street=='' || $building=='' || $email=='' || $password=='') { echo 'Please Fill All Fields'; } else { $query = "SELECT * from account WHERE number = '$number' "; $check = mysqli_fetch_array(mysqli_query($mysqli, $query)); if(isset($check)) { echo 'Account already exists'; } else { $query="INSERT INTO account (number,name,city,street,building,email,password) " . "VALUES('$number','$name','$city','$street','$building','$email','$password')"; if(mysqli_query($mysqli,$query)){ echo "Succesfully Registered."; } else { echo 'Something went wrong, Please try again later.'; } } mysqli_close($mysqli); } } else { echo 'Error'; } ?&gt; </code></pre> <p>My register android class:</p> <pre><code>public class register extends AppCompatActivity implements View.OnClickListener{ EditText rgNumber,rgPass,rgName,rgCity,rgBuilding,rgStr,rgEmail,rgPass2; Button bRegister,bCancel; private static final String RegisterURL="http://hssolutions.tk/ibd/includes/register_user.php"; @Override public void onClick(View v) { switch (v.getId()){ case R.id.bRegister: String password= rgPass.getText().toString().trim(); String password2 = rgPass2.getText().toString().trim(); if(password.equals(password2)){ registerUser(); } else{ showErrorMessage("Passwords don't match."); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); rgNumber = (EditText) findViewById(R.id.rgNumber); rgPass = (EditText) findViewById(R.id.rgPass); rgName = (EditText) findViewById(R.id.rgName); rgBuilding = (EditText) findViewById(R.id.rgBlding); rgCity = (EditText) findViewById(R.id.rgCity); rgStr= (EditText) findViewById(R.id.rgStr); rgEmail = (EditText) findViewById(R.id.rgEmail); rgPass2 = (EditText) findViewById(R.id.rgPass2); bRegister = (Button) findViewById(R.id.bRegister); bCancel = (Button) findViewById(R.id.bCancel); bRegister.setOnClickListener(this); } private void showErrorMessage(String error){ AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(register.this); dialogBuilder.setMessage(error); dialogBuilder.setPositiveButton("OK", null); dialogBuilder.show(); } private void registerUser(){ String number = rgNumber.getText().toString().trim(); String name = rgName.getText().toString().trim(); String city = rgCity.getText().toString().trim(); String building = rgBuilding.getText().toString().trim(); String street= rgStr.getText().toString().trim(); String email= rgEmail.getText().toString().trim(); String password= rgPass.getText().toString().trim(); register(number,name,city,building,street,email,password); } private void register(String number, String name, String city, String building, String street, String email, String password){ class RegisterUser extends AsyncTask&lt;String,Void,String&gt; { ProgressDialog loading; RegisterUserClass ruc=new RegisterUserClass(); @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(register.this,"Please Wait",null,true,true); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show(); } @Override protected String doInBackground(String... params) { HashMap&lt;String,String&gt; data=new HashMap&lt;String,String&gt;(); data.put("number",params[0]); data.put("name",params[1]); data.put("city",params[2]); data.put("street",params[3]); data.put("building",params[4]); data.put("email",params[5]); data.put("pass",params[6]); String result = ruc.sendPostRequest(RegisterURL,data); return result; } } RegisterUser ru= new RegisterUser(); ru.execute(number,name,city,street,building,email,password); } } </code></pre> <p>and the registration class which should send the requests:</p> <pre><code>public class RegisterUserClass { public String sendPostRequest(String requestURL, HashMap&lt;String, String&gt; postDataParams){ URL url; String response= ""; try { url= new URL(requestURL); HttpURLConnection con= (HttpURLConnection)url.openConnection(); con.setReadTimeout(15000); con.setConnectTimeout(15000); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); OutputStream os= con.getOutputStream(); BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(os,"UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode = con.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK) { BufferedReader reader= new BufferedReader(new InputStreamReader(con.getInputStream())); response=reader.readLine(); } } catch (Exception e) { e.printStackTrace(); } return response; } private String getPostDataString(HashMap&lt;String,String&gt; params) throws UnsupportedEncodingException { StringBuilder result= new StringBuilder(); boolean first = true; for(Map.Entry&lt;String,String&gt; entry:params.entrySet()){ if(first) { first=false; } else { result.append("&amp;"); } result.append(URLEncoder.encode(entry.getKey(),"UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(),"UTF-8")); } return result.toString(); } } </code></pre> <p>The application isnt showing an error, but the toast returns empty, while the database gets nothing inserted to it, i traced the code logically but still unable to find the error.</p> </div>

关于Android Studio与Bmob关联一直报错的问题

我在dependencies函数里添加那两行代码的时候报错 Error:(34, 13) Failed to resolve: cn.bmob.android:http-legacy:1.0 <a href="openFile:F:/Android Project/App04/app/build.gradle"> Show in File </a><br> <a href="open.dependency.in.project.structure"> Show in Project Structure dialog </a> Error:(33, 13) Failed to resolve: cn.bmob.android:bmob-sdk:3.6.6 <a href="openFile:F:/Android Project/App04/app/build.gradle"> Show in File </a><br> <a href="open.dependency.in.project.structure">Show in Project Structure dialog</a> 一直解决不了啊,各位大佬给支个招啊

为什么运行查询和删除数据库时闪退?

MainActivity ``` package com.example.administrator.diary; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button mm_login,yk_login; static final String db_pass="passwordDB"; static final String tb_pass="passwordTB"; SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //调用创建数据库方法 CREATE(); //调用按钮监听器方法 init(); //游客跳转 yk_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //为了跳转到日记界面,并实现日记功能 Intent YD=new Intent(MainActivity.this,DiaryActivity.class); startActivity(YD); } }); } //打开或创建数据库 public void CREATE(){ db = openOrCreateDatabase(db_pass, Context.MODE_PRIVATE, null); String createTable = " CREATE TABLE IF NOT EXISTS " + tb_pass + "(password_id VARCHAR (4) PRIMARY KEY)"; db.execSQL(createTable); } //获取activity_main的控件 public void init(){ mm_login=findViewById(R.id.but_mm_login); yk_login=findViewById(R.id.but_yk_login); //获取数据库数据项 Cursor cur=db.rawQuery("SELECT * FROM passwordTB",null); int amount=cur.getCount(); //数据库为0则表示没有密码存在数据库,密码跳转到注册密码界面,游客可直接登录日记界面 if (amount==0){ mm_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //为了跳转到注册界面,并实现注册功能 Intent MR=new Intent(MainActivity.this,RegisterActivity.class); startActivity(MR); } }); yk_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //为了跳转到日记界面,并实现日记功能 Intent YD=new Intent(MainActivity.this,DiaryActivity.class); startActivity(YD); } }); } else{//数据项不为0,则有密码已存在 mm_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //为了跳转到密码输入界面,并实现密码输入功能 Intent MS=new Intent(MainActivity.this,SendActivity.class); startActivity(MS); } }); //游客按钮隐藏 yk_login.setVisibility(Button.INVISIBLE); } } } ``` 登录代码 ``` package com.example.administrator.diary; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class SendActivity extends AppCompatActivity { Button log; EditText onesend,twosend; static final String db_pass="passwordDB"; static final String tb_pass="passwordTB"; SQLiteDatabase db; String f_send; String s_send; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send); //获取控件地址 log=findViewById(R.id.btn_log); onesend=findViewById(R.id.send); twosend=findViewById(R.id.resend); //获取密码 f_send = onesend.getText().toString(); s_send = twosend.getText().toString(); //打开或创建数据库 db=openOrCreateDatabase(db_pass, Context.MODE_PRIVATE,null); String createTable=" CREATE TABLE IF NOT EXISTS "+tb_pass+"(password VARCHAR (4))"; db.execSQL(createTable); //调用登录按钮方法 login(); } //对比输入密码和设置密码是否相同 private void check(){ //读取数据库中设置的密码 Cursor c=db.rawQuery("SELECT password FROM passwordTB",null); String p=c.getString(0); //判断是否相同 if (f_send.equals(p)&&s_send.equals(p)){ Toast.makeText(SendActivity.this,"登录成功",Toast.LENGTH_SHORT).show(); //判断相同后跳转到日记界面 Intent SD=new Intent(SendActivity.this,DiaryActivity.class); startActivity(SD); } //不同提醒用户 else Toast.makeText(SendActivity.this,"密码输入不对,请重新输入",Toast.LENGTH_SHORT).show(); } //登录按钮功能 private void login(){ log.setOnClickListener(new View.OnClickListener() { @Override //监听器 public void onClick(View v) { //调用检验密码方法 check(); } }); } } ``` 删除数据库代码 ``` package com.example.administrator.diary; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; public class DiaryActivity extends AppCompatActivity { private Button de; static final String db_pass="passwordDB"; static final String tb_pass="passwordTB"; SQLiteDatabase db; Cursor cursor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_diary); //获取控件位置 de=findViewById(R.id.delete); //打开或创建数据库 db=openOrCreateDatabase(db_pass, Context.MODE_PRIVATE,null); String createTable=" CREATE TABLE IF NOT EXISTS "+tb_pass+"(password VARCHAR (4))"; db.execSQL(createTable); Ondelete(); } //删除密码按钮方法 private void Ondelete(){ de.setOnClickListener(new View.OnClickListener() { @Override //监听器 public void onClick(View v) { //删除数据表方法 String sql = "delete from passwordTB where id = 0"; db.execSQL(sql); Toast.makeText(DiaryActivity.this,"删除成功",Toast.LENGTH_SHORT).show(); } }); } } ``` 建表插表代码 ``` //打开或创建数据库 db=openOrCreateDatabase(db_pass, Context.MODE_PRIVATE,null); String createTable=" CREATE TABLE IF NOT EXISTS "+tb_pass+"(password VARCHAR (4))"; db.execSQL(createTable); compare(); zc(); } //添加新密码到数据库中 private void addData(String password){ ContentValues cv=new ContentValues(1); cv.put(" password",password); db.insert(tb_pass,null,cv); } ``` 闪退后报错 ``` 2020-02-04 17:22:49.787 15729-15729/com.example.administrator.diary E/SQLiteLog: (1) no such column: id 2020-02-04 17:22:49.787 15729-15729/com.example.administrator.diary D/AndroidRuntime: Shutting down VM 2020-02-04 17:22:49.788 15729-15729/com.example.administrator.diary E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.administrator.diary, PID: 15729 android.database.sqlite.SQLiteException: no such column: id (code 1 SQLITE_ERROR): , while compiling: delete from passwordTB where id = 0 at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:985) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:592) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590) at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61) at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:33) at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1802) at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1730) at com.example.administrator.diary.DiaryActivity$1.onClick(DiaryActivity.java:39) at android.view.View.performClick(View.java:6913) at android.view.View.performClickInternal(View.java:6890) at android.view.View.access$3200(View.java:792) at android.view.View$PerformClick.run(View.java:27158) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:209) at android.app.ActivityThread.main(ActivityThread.java:7021) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872) ``` 程序可以运行,但点击登录按钮或删除按钮后都会返回到mainactivity的界面,再按一次登录或删除就崩溃了,而且还没有达到删除数据库的目的,有大神知道是哪里出问题了吗?

Android studio访问mysql闪退,本地测试可以

使用为mysql-connector-java-8.0.16.jar以及mysql8.0.19 在本地测试通过 public class DBUtils { private static String driver = "com.mysql.cj.jdbc.Driver";//MySQL 驱动 private static String url = "jdbc:mysql://192.168.2.146:3306/helper?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";//MYSQL数据库连接Url private static String user = "wang";//用户名 private static String password = "Imissyou**";//密码 private static Connection getConnection() { Connection conn = null; try { Class.forName(driver); // conn = DriverManager.getConnection(url,user,password); } catch (SQLException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } return conn; } public static Map<String, String> login(User user) { HashMap<String, String> map = new HashMap<>(); Connection conn = getConnection(); try { Statement st = conn.createStatement(); String sql= "select * from user where username ='" + user.getUsername() + "' and password ='" + user.getPassword() + "'"; ResultSet res = st.executeQuery(sql); if (res == null) { return null; } else { int cnt = res.getMetaData().getColumnCount(); res.next(); for (int i = 1; i <= cnt; ++i) { String field = res.getMetaData().getColumnName(i); map.put(field, res.getString(field)); } conn.close(); st.close(); res.close(); return map; } } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String []args){ User user = new User("aaa","123456"); Map<String,String> result= DBUtils.login(user); System.out.println(result); } } 但是在主界面绑定事件,访问数据库时直接闪退并报错 ![图片说明](https://img-ask.csdn.net/upload/202003/15/1584252548_20385.jpg) 主界面代码如下: package com.example.helper; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.StrictMode; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.Map; public class MainActivity extends AppCompatActivity { private Button register; private Button login_user; private TextView forget_password; private TextView login_visitor; private EditText et_username; private EditText et_password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化控件 init(); //注册界面跳转 register.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ Intent intent = new Intent(MainActivity.this, RegisterActivity.class); startActivity(intent); } }); //登录功能未加载,等待后台数据库完善 login_user.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String username = et_username.getText().toString(); //获取用户名 String password = et_password.getText().toString(); //获取密码 if(TextUtils.isEmpty(username)){ Toast.makeText(MainActivity.this,"请输入用户名",Toast.LENGTH_SHORT).show(); } else if(TextUtils.isEmpty(password)){ Toast.makeText(MainActivity.this,"请输入密码",Toast.LENGTH_SHORT).show(); } //本地管理员帐号 else if(username.equals("admin")&&password.equals("admin")){ Intent intent = new Intent(MainActivity.this,HomePageActivity.class); startActivity(intent); } //else Toast.makeText(MainActivity.this,"未连接后台数据库",Toast.LENGTH_SHORT).show(); else{ User user = new User(username,password); checkLogin(user); //Toast.makeText(MainActivity.this,"已获取"+username+" "+password,Toast.LENGTH_SHORT).show(); } } }); //首页跳转 login_visitor.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ Intent intent = new Intent(MainActivity.this, HomePageActivity.class); startActivity(intent); } }); //找回密码界面跳转 forget_password.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this,ForgetPasswordActivity.class); startActivity(intent); } }); } private void init() { et_username = findViewById(R.id.et_username); et_password = findViewById(R.id.et_password); register = findViewById(R.id.btn_2); login_user = findViewById(R.id.btn_1); login_visitor = findViewById(R.id.login_visitor); forget_password = findViewById(R.id.forget_password); } class DBThread implements Runnable { private User user; private Context context; public void setUser(User user) { this.user = user; } public void setContext(Context context) { this.context = context; } @Override public void run() { Map<String,String> result= DBUtils.login(user); /* if (result != null && result.size() > 0) { Intent intent = new Intent(MainActivity.this,HomePageActivity.class); Toast.makeText(MainActivity.this,"有此帐号",Toast.LENGTH_SHORT).show(); startActivity(intent); } */ } } private void checkLogin(User u) { DBThread dt = new DBThread(); dt.setUser(u); dt.setContext(MainActivity.this); Thread thread = new Thread(dt); thread.start(); } }

android studio sqlite数据库,sqlite error: no such table:user

sqlite总是报错,(安装到真机)。databases里面也有表,把它导出,在DB Broswer里却看不到数据。 ![图片说明](https://img-ask.csdn.net/upload/201907/22/1563776644_924445.png) ![图片说明](https://img-ask.csdn.net/upload/201907/22/1563776842_633436.png)![图片说明](https://img-ask.csdn.net/upload/201907/22/1563776853_202929.png)![图片说明](https://img-ask.csdn.net/upload/201907/22/1563776864_605326.png)![图片说明](https://img-ask.csdn.net/upload/201907/22/1563776889_876108.png)![图片说明](https://img-ask.csdn.net/upload/201907/22/1563776906_474787.png)

android studio编译无错误,运行时显示,但点击button不响应按键事件

原因:自从Android 3.2(API 13),screen size也开始跟着设备的横竖切换而改变。这会导致activity重新加载 方法:在AndroidManifest.xml里设置的MiniSdkVersion和 TargetSdkVersion属性大于等于13的情况下,如果你想阻止程序在运行时重新加载Activity,除了设     置"orientation",你还必须设置"ScreenSize"。(AndroidManifest.xml中设置android:configChanges="orientation|screenSize“)

android APP连接mysql时,APP闪退

安卓程序连接MySQL一直不成功,本地连接可以。我是用手机调试的,点击接mysql按钮时,APP闪退。在网上找了好多方法都不行。求看看什么问题 错误日志如下: 2019-08-25 08:25:33.377 5570-5570/mark.zhang E/AndroidRuntime: FATAL EXCEPTION: main Process: mark.zhang, PID: 5570 java.lang.IllegalStateException: Could not execute method for android:onClick at android.view.View$DeclaredOnClickListener.onClick(View.java:5692) at android.view.View.performClick(View.java:6663) at android.view.View.performClickInternal(View.java:6635) at android.view.View.access$3100(View.java:794) at android.view.View$PerformClick.run(View.java:26199) at android.os.Handler.handleCallback(Handler.java:907) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:216) at android.app.ActivityThread.main(ActivityThread.java:7625) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at android.view.View$DeclaredOnClickListener.onClick(View.java:5687) at android.view.View.performClick(View.java:6663)  at android.view.View.performClickInternal(View.java:6635)  at android.view.View.access$3100(View.java:794)  at android.view.View$PerformClick.run(View.java:26199)  at android.os.Handler.handleCallback(Handler.java:907)  at android.os.Handler.dispatchMessage(Handler.java:105)  at android.os.Looper.loop(Looper.java:216)  at android.app.ActivityThread.main(ActivityThread.java:7625)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)  Caused by: java.lang.BootstrapMethodError: Exception from call site #39 bootstrap method at com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.<clinit>(AbandonedConnectionCleanupThread.java:58) at java.lang.Class.classForName(Native Method) at java.lang.Class.forName(Class.java:453) at java.lang.Class.forName(Class.java:378) at com.mysql.cj.jdbc.NonRegisteringDriver.<clinit>(NonRegisteringDriver.java:99) at java.lang.Class.classForName(Native Method) at java.lang.Class.forName(Class.java:453) at java.lang.Class.forName(Class.java:378) at mark.zhang.Util.openConnection(Util.java:16) at mark.zhang.Main.onConn(Main.java:30) at java.lang.reflect.Method.invoke(Native Method)  at android.view.View$DeclaredOnClickListener.onClick(View.java:5687)  at android.view.View.performClick(View.java:6663)  at android.view.View.performClickInternal(View.java:6635)  at android.view.View.access$3100(View.java:794)  at android.view.View$PerformClick.run(View.java:26199)  at android.os.Handler.handleCallback(Handler.java:907)  at android.os.Handler.dispatchMessage(Handler.java:105)  at android.os.Looper.loop(Looper.java:216)  at android.app.ActivityThread.main(ActivityThread.java:7625)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)  Caused by: java.lang.ClassCastException: Bootstrap method returned null at com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.<clinit>(AbandonedConnectionCleanupThread.java:58)  at java.lang.Class.classForName(Native Method)  at java.lang.Class.forName(Class.java:453)  at java.lang.Class.forName(Class.java:378)  at com.mysql.cj.jdbc.NonRegisteringDriver.<clinit>(NonRegisteringDriver.java:99)  at java.lang.Class.classForName(Native Method)  at java.lang.Class.forName(Class.java:453)  at java.lang.Class.forName(Class.java:378)  at mark.zhang.Util.openConnection(Util.java:16)  at mark.zhang.Main.onConn(Main.java:30)  at java.lang.reflect.Method.invoke(Native Method)  at android.view.View$DeclaredOnClickListener.onClick(View.java:5687)  at android.view.View.performClick(View.java:6663)  at android.view.View.performClickInternal(View.java:6635)  at android.view.View.access$3100(View.java:794)  at android.view.View$PerformClick.run(View.java:26199)  at android.os.Handler.handleCallback(Handler.java:907)  at android.os.Handler.dispatchMessage(Handler.java:105)  at android.os.Looper.loop(Looper.java:216)  at android.app.ActivityThread.main(ActivityThread.java:7625)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)  2019-08-25 08:25:33.398 5570-5570/mark.zhang I/Process: Sending signal. PID: 5570 SIG: 9 源码如下: 这是util.java ``` package mark.zhang; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Util { public static Connection openConnection(String url, String user, String password) { Connection conn = null; try { final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver"; Class.forName(DRIVER_NAME); conn = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException e) { conn = null; } catch (SQLException e) { conn = null; } return conn; } public static void query(Connection conn, String sql) { if (conn == null) { return; } Statement statement = null; ResultSet result = null; try { statement = conn.createStatement(); result = statement.executeQuery(sql); if (result != null && result.first()) { int idColumnIndex = result.findColumn("id"); int nameColumnIndex = result.findColumn("name"); System.out.println("id\t\t" + "name"); while (!result.isAfterLast()) { System.out.print(result.getString(idColumnIndex) + "\t\t"); System.out.println(result.getString(nameColumnIndex)); result.next(); } } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (result != null) { result.close(); result = null; } if (statement != null) { statement.close(); statement = null; } } catch (SQLException sqle) { } } } public static boolean execSQL(Connection conn, String sql) { boolean execResult = false; if (conn == null) { return execResult; } Statement statement = null; try { statement = conn.createStatement(); if (statement != null) { execResult = statement.execute(sql); } } catch (SQLException e) { execResult = false; } return execResult; } } ``` 这是main.java ``` package mark.zhang; import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread; import java.sql.Connection; import java.sql.SQLException; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.os.Bundle; import android.view.View; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Main extends Activity { private static final String REMOTE_IP = "223.104.64.237"; private static final String URL = "jdbc:mysql://223.104.64.237:3306/mydb?useSSL=false&serverTimezone=GMT&characterEncoding=utf-8&autoReconnect=true"; private static final String USER = "root"; private static final String PASSWORD = "123"; private Connection conn; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void onConn(View view) { conn = Util.openConnection(URL, USER, PASSWORD); /* final Thread thread = new Thread(new Runnable() { @Override public void run() { // 反复尝试连接,直到连接成功后退出循环 while (!Thread.interrupted()) { try { Thread.sleep(100); // 每隔0.1秒尝试连接 } catch (InterruptedException e) { System.out.println("链接数据库"); } // 2.设置好IP/端口/数据库名/用户名/密码等必要的连接信息 String url="jdbc:mysql://223.104.64.237:3306/mydb?useSSL=false&serverTimezone=Hongkong&characterEncoding=utf-8&autoReconnect=true"; String user = "root"; String password = "123"; // 3.连接JDBC try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection(url,user,password); System.out.println("远程连接成功!"); conn.close(); return; } catch (SQLException e) { System.out.println("远程连接失败!"); } catch (ClassNotFoundException e){ } } } }); thread.start();*/ } public void onInsert(View view) { String sql = "insert into mytable values(9, 'hanmeimei')"; Util.execSQL(conn, sql); } public void onDelete(View view) { String sql = "delete from mytable where name='mark'"; Util.execSQL(conn, sql); } public void onUpdate(View view) { String sql = "update mytable set name='李磊' where name='韩美'"; Util.execSQL(conn, sql); } public void onQuery(View view) { System.out.println("All users info:"); Util.query(conn, "select * from mytable"); } @Override protected void onDestroy() { super.onDestroy(); if (conn != null) { try { conn.close(); } catch (SQLException e) { conn = null; } finally { conn = null; } } } } ```

在Android Studio使用jdbc连接MySQL遇到java.lang.ExceptionInInitializerError

使用jdbc的方法在安卓项目中连接MySQL数据库,在getConnection()时出现java.lang.ExceptionInInitializerError,实在不懂错在哪了... ![图片说明](https://img-ask.csdn.net/upload/201910/21/1571662749_861983.png)

Android studio在Java工程中导入mysql的jar包遇到问题

![图片说明](https://img-ask.csdn.net/upload/201804/01/1522568697_950587.png) 不是Android工程。。。。

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

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

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

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

点沙成金:英特尔芯片制造全过程揭密

“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

我说我不会算法,阿里把我挂了。

不说了,字节跳动也反手把我挂了。

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你打算用Java 8一辈子都不打算升级到Java 14,真香

我们程序员应该抱着尝鲜、猎奇的心态,否则就容易固步自封,技术停滞不前。

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

一文带你入门Java Stream流,太强了

两个星期以前,就有读者强烈要求我写一篇 Java Stream 流的文章,我说市面上不是已经有很多了吗,结果你猜他怎么说:“就想看你写的啊!”你看你看,多么苍白的喜欢啊。那就“勉为其难”写一篇吧,嘻嘻。 单从“Stream”这个单词上来看,它似乎和 java.io 包下的 InputStream 和 OutputStream 有些关系。实际上呢,没毛关系。Java 8 新增的 Stream 是为...

立即提问
相关内容推荐