- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我已经根据以下链接https://www.youtube.com/watch?v=M4VTi5-Aw20上的教程创建了一个Android应用程序这些是文件,FetchUserData.php
<?php
//database connection
$host = 'localhost';
$user1 = 'root';
$password1 = '';
$database = 'users';
$con = mysqli_connect($host, $user1, $password1, $database);
//checking the validity of the database
// if(!$con){
//die("connection Failed" . mysqli_connect_error());}
//echo "connected Successfully";
$password=$_POST["password"];
$userName=$_POST["userName"];
$statement=mysqli_prepare($con,"SELECT * FROM usersLogged WHERE userName=? AND password=?");
//to prevent from sql injection
mysqli_stmt_bind_param($statement,"ss",$userName,$password);
mysqli_stmt_execute($statement);
//after executing the command we need to get the results that were selected
mysqli_stmt_store_result($statement); //storing the results in a buffer for temporary
//we need to bind the results
mysqli_stmt_bind_result($statement, $userId, $userName, $firstName, $lastName, $password, $age);
//now we need to store them into an array
$user=array();
//this while loop is going to run only once
while(mysqli_stmt_fetch($statement)){
//storing the values which are fetched from the database are kept in the array(#user)
$user[userName]=$userName;
$user[firstName]=$firstName;
$user[lastName]=$lastName;
$user[password]=$password;
$user[age]=$age;
//now we need to pass the content to the phone,we send the array in a json
json_encode($user);
mysqli_stmt_close($statement);
mysqli_close($con);
}
?>
这是我的RequestServer.java
package com.example.kasun.timetable;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ProgressBar;
import org.apache.http.HttpConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by kasun on 1/7/16.
*/
public class RequestServer {
ProgressDialog progressDialog; // loads the pregress dialog
private static final int CONNECTION_TIMEOUT = 1000 * 5;
private static final String SERVER_ADDRESS = "http://10.111.97.94/Timetable/";
//constructor
//we can't initialize progress dialog as this is not a java class that is associcated with an activity
public RequestServer(Context context) {
progressDialog = new ProgressDialog(context); // progressDialog is initialized
progressDialog.setTitle("Processing");
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
//users can't cancel the fetch
}
public void storeUserDataInBackground(User user, GetUserCallBack getUserCallBack) {
progressDialog.show();
new storeUserDataAsyncTask(user, getUserCallBack).execute();
/* here we need to create an object for it as it is a class, from this code the constructor
of the AsyncClass will be run
*/
}
public void fetchUserDataInBackground(User user, GetUserCallBack callBack) {
progressDialog.show();
new fetchUserDataAsyncTask(user,callBack).execute();
}
/*we need t create inner class, which is the background class which runs, backgrounds classes in android are known as
Async tasks
*/
public class storeUserDataAsyncTask extends AsyncTask<Void, Void, Void>
{
/* void = we are not sending anything to this task when it is being executed
void= we are not asking any progress from the AsyncTask as we are running the
progressDialog( how we need the AsyncTask show the progress to the user)
void= what this should return
*/
User user;
GetUserCallBack getUserCallBack;
public storeUserDataAsyncTask(User user, GetUserCallBack getUserCallBack) {
this.user = user;
this.getUserCallBack = getUserCallBack;
}
@Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("userName", user.userName));
dataToSend.add(new BasicNameValuePair("firstName", user.firstName));
dataToSend.add(new BasicNameValuePair("lastName", user.lastName));
dataToSend.add(new BasicNameValuePair("password", user.password));
dataToSend.add(new BasicNameValuePair("age", user.age + ""));
/*setting the attributes for the httpRequest we are going to make( attributes for the
http_post
*/
HttpParams httpRequestParams = new BasicHttpParams();
//going to set the attributes
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
//waiting for the changes to be made to the localhost
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
//waiting till data is received from the server
//-----------setting up the http request is finished
//setting up a client, client can only do is make a request to the server0
HttpClient client = new DefaultHttpClient(httpRequestParams);
//client must perform duties according to the attributes mentioned in the httpRequestParams
//setting the post method, post is used to store the data that is used to send to the database
HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php"); // sets the server address
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
//this method runs after the saving data to the server is completed
progressDialog.dismiss();
getUserCallBack.done(null);
super.onPostExecute(aVoid);
}
}
//--------------- for fetching the user data from the database
public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User>
{
/* Void = we are not sending anything to this task when it is being executed
Void= we are not asking any progress from the AsyncTask as we are running the
progressDialog( how we need the AsyncTask show the progress to the user)
user= what this should return
*/
User user;
GetUserCallBack getUserCallBack;
public fetchUserDataAsyncTask(User user, GetUserCallBack getUserCallBack) {
this.user = user;
this.getUserCallBack = getUserCallBack;
}
@Override
protected User doInBackground(Void... voids) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("userName", user.userName));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
User returnedUser=null;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
/*after excuting this
will return the detials of the user
*/
// we need to convert them so that we can use them
HttpEntity entity= httpResponse.getEntity();
// now details are stored as entities
// now we need to conevert them to string
String result= EntityUtils.toString(entity);
/* we passed data to the phone from the servse through a Json object, so we need to
take the details send through the json object
*/
JSONObject jsonObject= new JSONObject(result);
// if there are no details are send through the JSON object,
if(jsonObject.length()==0){
returnedUser=null;
}
else{
String firstName=jsonObject.getString("firstName");
String lastName=jsonObject.getString("lastName");
int age= jsonObject.getInt("age");
returnedUser= new User(firstName,lastName,user.userName,user.password,age);
}
} catch (Exception e) {
e.printStackTrace();
}
return returnedUser;
}
@Override
protected void onPostExecute(User returnedUser) {
//this method runs after the saving data to the server is completed
progressDialog.dismiss();
getUserCallBack.done(returnedUser);
super.onPostExecute(returnedUser);
}
}
}
这是 UserLocalDatabase.java
package com.example.kasun.timetable;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by kasun on 12/31/15.
*/
public class UserLocalDatabase {
private static final String DB_name = "userDetails";
// this is the name of the database which is used to store the data in the phone
SharedPreferences userDataBase;
/*SharedPreferences is the thing that stores data in the phone, here userDatabase is the object
of the SharedPreference, DB_name is the file which is used by that object for storing data
*/
//constructor
public UserLocalDatabase(Context context) {
/* SharedPreference can only be initialize from an activity, since UserLocalDatabase is a seperate java
class, it can't initialize the SharedPreference, so we want all the activities that uses the
SharedPreference to send their Context to this method so that, then we can initialize the Shared Preference
*/
//initializing the SharedPreference through the context passed by the activity
userDataBase = context.getSharedPreferences(DB_name, 0);
//DB_name is the file where the SharedPreferences values are coming from,
//0 is the default value
}
//initializing the SharedPreference through the context passed by the activity is finished
// methods for the adding and substracting
public void storeUserData(User user) {
// and object of User class is being passed to here
// adding the editable function in SharedPreference
SharedPreferences.Editor spEditor = userDataBase.edit();
spEditor.putString("firstName", user.firstName);
spEditor.putString("lastName", user.lastName);
spEditor.putString("userName", user.userName);
spEditor.putString("password", user.password);
spEditor.putInt("age", user.age);
spEditor.commit();
// commit is need to delete or add a data to the SharePreference
/*spEditor is an object of the SharedPreference and it uses the SharedPreference edit()
method through the object
*/
/*
here the values are obtained from the User class attributes and they are stored in the SharedPreference
*/
}
public User getLoggedInUser() {
// getting data from the SharedPreference
SharedPreferences.Editor spEditor = userDataBase.edit();
String firstName = userDataBase.getString("firstName", "");
String lastName = userDataBase.getString("lastName", "");
String userName = userDataBase.getString("userName", "");
String password = userDataBase.getString("password", "");
int age = userDataBase.getInt("age", -1);
// here -1 is needed as this is an integer values
// here values are being passed to the User class
User userLoggedIn = new User(firstName, lastName, userName, password, age);
return userLoggedIn;
// any method calls this method get the details of the user logged
}
// to check whether the user has logged into the system
public void setUserStatus(Boolean status) {
SharedPreferences.Editor spEditor = userDataBase.edit();
spEditor.putBoolean("status", status);
}
public boolean getUserStatus() {
if (userDataBase.getBoolean("status", false) == true) {
//this checks the status field in the userDatabase.
//("status",false) this boolean value is the default values for the "status" field
return true;
} else {
return false;
}
}
public void clear() {
SharedPreferences.Editor spEditor = userDataBase.edit();
spEditor.clear(); //after clearing also commit should be done
spEditor.commit();
}
}
这是 User.java
package com.example.kasun.timetable;
/**
* Created by kasun on 12/31/15.
*/
public class User {
//user details
String firstName,lastName,userName,password;
int age;
public User(String firstName, String lastName,String username, String password,int age){
this.firstName=firstName;
this.lastName=lastName;
this.userName=username;
this.password=password;
this.age=age;
}
public User(String username, String password){
this.userName=username;
this.password=password;
this.age=-1;
this.firstName="";
this.lastName="";
}
}
当我要登录时会弹出这些错误
W/System.err:位于 com.example.kasun.timetable.RequestServer$fetchUserDataAsyncTask.doInBackground(RequestServer.java:195)
这是一行
JSONObject jsonObject= new JSONObject(result);
W/System.err:位于 com.example.kasun.timetable.RequestServer$fetchUserDataAsyncTask.doInBackground(RequestServer.java:140)
这是哪条线
public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User>
请帮我解决这个问题
最佳答案
我解决了这个问题,问题是应用程序无法读取 htdocs 目录中的 FetchUserData.php。我使用
将权限更改为 777sudo chmod 777 -R /opt/lammp/htdocs
现在好了。
关于java - W/System.err : org. json.JSONException : Value <br of type java. lang.String 无法转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34703386/
在 Tomcat 6/Ubuntu 12.04 上启动 Grails 2.1.0 应用程序时出现以下错误。 Error 500 - Internal Server Error. groovy.lang
在运行 Storm 拓扑时,我收到此错误。拓扑完美运行 5 分钟,没有任何错误,然后失败。我正在使用 Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS as 300 sec i
我有一个 jsp 代码在其中一台机器上运行良好。但是当我复制到另一台机器时,我得到了这个 no such method found 异常。我是 Spring 的新手。有人可以解释我错过了什么吗? 以下
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我的代码在下面给出了一个错误; Exception in thread "main" java.lang.NoSuchMethodError: com/myApp/Client.cypherCBC(L
我正在尝试一个 Restful web 服务示例,所以当我要访问 url 时,我遇到了异常 java.lang.NoSuchMethodError: jersey.repackaged.com.goo
我正在将一个 Spring web 项目转换为一个 Maven 项目,但我收到了这个错误: java.lang.NoSuchMethodError: org.jboss.logging.Logger.
在我的项目中,我有一个像这样的枚举: public enum MyEnum { FIRST(1), SECOND(2); private int value; private MyEnum(int v
我创建了这个简单的示例,用于读取 Linux 正常运行时间: public String getMachineUptime() throws IOException { String[] di
我正在使用 Eclipse,并且正在使用 Java。我的目标是使用 bogoSort 方法对 vector 进行排序在一个 vector (vectorExample)中适应我的 vector 类型,
我正在运行以下查询。它显示一条错误消息。如何解决这个错误? ListrouteList=null; List companyList = session.createS
我有以下模型类: @Entity @Table(name="user_content") @org.hibernate.annotations.NamedQueries({ @org.
我有那个错误。这是我的代码: GmailSettingsService service = new GmailSettingsService(APPLICATION_NAME, DOMAIN_NAME
实际上我在执行我的java程序时遇到了下面提到的错误 Exception in thread "pool-1-thread-1" java.lang.ClassCastException: jav
java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.String 我在以下代码中遇到此异常: Strin
我正在尝试从 linkedhashset 中检索随机元素。下面是我的代码,但它每次都给我异常。 private static void generateRandomUserId(Set userIds
我已经完成了 Android 中的代码: List spinnerArray = new ArrayList(); for (int i = 0; i item = (LinkedTreeMap)
这个问题已经有答案了: Explanation of ClassCastException in Java (12 个回答) 已关闭 6 年前。 我已经编写了 java 到 Json 的代码,同时从页
这个问题在这里已经有了答案: ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn (4 个答案) 关闭 6 年前
我在运行时遇到问题来编译这段代码,这给我一个错误,java.lang.Integer 无法转换为 Java.lang.Double。如果有人帮助我更正此代码,我将非常高兴 double x; pu
我是一名优秀的程序员,十分优秀!