我正在开发一个基于远程数据库的Android应用程序,我找到了如何将数据放入数据库的解决方案,但是我遇到了很多问题。 当我打开获取数据的活动时,应用程序崩溃。我无法本地化我的代码中的错误!所以这是我的代码,我希望你能帮助我。 谢谢。
这是“Acceuil”类,有1个按钮可以打开“教授”类。
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
//in this class I'm just defining a button that will open another class to get data from the database.
public class Acceuil extends Activity {
Button b1;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.acceuil);
b1 = (Button) findViewById(R.id.button3);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Professors.class);
startActivity(i);
}
});
}
}
这是崩溃我的应用程序的“教授”课程。
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Professors extends Activity {
//URL to get JSON Array
private static String url = "http://waelhamda.host22.com/comments.php";
//JSON Node Names
private static final String TAG_USER = "posts";
private static final String TAG_ID = "last";
JSONArray user = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.professors);
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
//Importing TextView
final TextView uid = (TextView)findViewById(R.id.pro1);
//Set JSON Data in TextView
uid.setText(id);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
这是“JSONParser”类。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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 + "\n");
}
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> 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 + "\n");
}
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
最后这是应用程序的清单文件。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wael.enimcommunity"
android:versionCode="1"
android:versionName="1.0" >
<meta-data android:name="com.google.android.backup.api_key"
android:value="AEdPqrEAAAAIdPJ8uLgoiErqlZNYU5_jN_d8O8VPPtfbbF5MRQ" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.wael.enimcommunity.Login"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.wael.enimcommunity.Register"
android:label="@string/app_name" >
</activity>
<activity
android:name="com.wael.enimcommunity.Acceuil"
android:label="@string/app_name" >
</activity>
<activity
android:name="com.wael.enimcommunity.JSONParser"
android:label="@string/app_name" >
</activity>
<activity
android:name="com.wael.enimcommunity.GPSTracker"
android:label="@string/app_name" >
</activity>
<activity
android:name="com.wael.enimcommunity.Events"
android:label="@string/app_name" >
</activity>
<activity
android:name="com.wael.enimcommunity.Professors"
android:label="@string/app_name" >
</activity>
<activity
android:name="com.wael.enimcommunity.Portail"
android:label="@string/app_name" >
</activity>
<activity
android:name="com.wael.enimcommunity.Schedule"
android:label="@string/app_name" >
</activity>
</application>
</manifest>
我希望这些信息足以解决我的问题。再次谢谢我的朋友。
答案 0 :(得分:1)
您是主线程中的网络。你需要先解决这个问题。
使用AsyncTask
示例:
private TextView uid; // Define global
在onCreate
uid = (TextView)findViewById(R.id.pro1);
new MyAsyncTask().execute();
内心课
public class MyAsyncTask extends AsyncTask<Void, Void, String> {
@Override
public String doInBackground(Void a) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
return id;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public void onPostExecute(String result) {
uid.setText(result);
}
}
答案 1 :(得分:0)
网络运营可能涉及不可预测的延迟。为防止此操作导致糟糕的用户体验,请始终在UI的单独线程上执行网络操作。 AsyncTask类提供了从UI线程启动新任务的最简单方法之一。