此应用程序具有登录页面,我将其作为MainActivity创建,并添加了一个包含一些片段的新活动。在其中一个片段中,我试图使用jdbc在Fragment中执行SQL查询。
我是Android开发的新手。当我按应执行SQL查询的片段上的按钮时,应用程序不断崩溃。以下是我的片段Java类代码:
package com.alert.tcsapps;
import android.content.Context;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment implements View.OnClickListener {
private ArrayList<ClassListItems> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
private ListView listView; // ListView
private Button gButton;
private ConnectionClass connectionClass;
EditText username, password;
Connection con;
String un, pass, db, ip;
Boolean isSuccess = false;
public HomeFragment() {
// Required empty public constructor
}
//@Override
public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState) {
View myView = inflater.inflate(R.layout.fragment_home, container, false);
gButton = (Button) myView.findViewById(R.id.btnGet);
gButton.setOnClickListener(this);
listView = (ListView) myView.findViewById(R.id.listView); //ListView Declaration
itemArrayList = new ArrayList<ClassListItems>(); // Arraylist Initialization
username = (EditText) myView.findViewById(R.id.edittext_username);
return myView;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnGet:
String usernam = username.getText().toString();
try {
Connection conn = connectionClass.CONN(); // Connect to database
if (con == null) {
Toast.makeText(getActivity(), "Invalid Credentials!", Toast.LENGTH_LONG).show();
} else {
String query = "select * from TCSAPPS where email= '" + usernam.toString() + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
while (rs.next()) {
try {
itemArrayList.add(new ClassListItems(rs.getString("name"), rs.getString("email"), rs.getString("password")));
} catch (Exception ex) {
Toast.makeText(getActivity(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
isSuccess = true;
}
} else {
isSuccess = false;
}
}
} catch (Exception ex) {
isSuccess = false;
Toast.makeText(getActivity(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Setup any handles to view objects here
// EditText etFoo = (EditText) view.findViewById(R.id.etFoo);
}
public void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my ListView
{
Toast.makeText(getActivity(), msg + "", Toast.LENGTH_LONG).show();
if (isSuccess == false) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, getActivity());
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
public class MyAppAdapter extends BaseAdapter //has a class viewholder which holds
{
public class ViewHolder {
TextView textName;
TextView textEmail;
TextView textPassword;
}
public List<ClassListItems> loginList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context) {
this.loginList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(loginList);
}
@Override
public int getCount() {
return loginList.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.list_content, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = (TextView) rowView.findViewById(R.id.textName);
viewHolder.textEmail = (TextView) rowView.findViewById(R.id.textEmail);
viewHolder.textPassword = (TextView) rowView.findViewById(R.id.textPassword);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(loginList.get(position).getName() + "");
viewHolder.textEmail.setText(loginList.get(position).getName() + "");
viewHolder.textPassword.setText(loginList.get(position).getName() + "");
return rowView;
}
}
}
以下是“运行”错误日志:
07/01 12:54:39: Launching app
$ adb shell am start -n "com.alert.tcsapps/com.alert.tcsapps.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 14794 on device emulator-5554
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/m.alert.tcsapp: JIT profile information will not be recorded: profile file does not exits.
I/chatty: uid=10085(com.alert.tcsapps) identical 10 lines
W/m.alert.tcsapp: JIT profile information will not be recorded: profile file does not exits.
I/InstantRun: starting instant run server: is main process
W/m.alert.tcsapp: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
W/m.alert.tcsapp: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
I/m.alert.tcsapp: Background concurrent copying GC freed 6290(2MB) AllocSpace objects, 0(0B) LOS objects, 52% free, 1379KB/2MB, paused 1.542ms total 138.604ms
D/OpenGLRenderer: HWUI GL Pipeline
D/: HostConnection::get() New Host Connection established 0xe2ccffc0, tid 14817
I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/OpenGLRenderer: Swap behavior 0
D/EGL_emulation: eglCreateContext: 0xe2cffd00: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xe2cffd00: ver 2 0 (tinfo 0xdb58e190)
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@a5aca53
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.alert.tcsapps, PID: 14794
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.alert.tcsapps.HomeFragment.onViewCreated(HomeFragment.java:90)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1471)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3273)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:620)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1391)
at android.app.Activity.performStart(Activity.java:7157)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:2937)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I/Process: Sending signal. PID: 14794 SIG: 9
Application terminated.
谁能告诉我我在代码中做错了什么吗?谢谢。