Android的连接MySQL数据库...应用程序结束 [英] Connecting android to mysql database... application ends
本文介绍了Android的连接MySQL数据库...应用程序结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试我的应用程序连接到MySQL数据库的应用程序突然停止。我认为这个问题是与我写的jasonparsor类。我需要接受申请,而无需缴纳任何事情。我应该怎么改变我的班..
以下
包com.mahavega.qcdemo;进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;
进口的java.util.List;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.client.utils.URLEn codedUtils;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.util.Log;公共类JSONParser { 静态InputStream为= NULL;
静态的JSONObject jObj = NULL;
静态JSON字符串=; //构造
公共JSONParser(){ } //函数得到JSON的网址
//通过HTTP POST或GET方法
公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,
清单<&的NameValuePair GT; PARAMS){ //使HTTP请求
尝试{ //检查请求的方法
如果(方法==POST){
//请求方法是POST
// defaultHttpClient
DefaultHttpClient的HttpClient =新DefaultHttpClient();
HttpPost httpPost =新HttpPost(URL);
httpPost.setEntity(新UrlEn codedFormEntity(PARAMS)); HTT presponse HTT presponse = httpClient.execute(httpPost);
HttpEntity httpEntity = HTT presponse.getEntity();
是= httpEntity.getContent(); }否则如果(方法==GET){
//请求方法是GET
DefaultHttpClient的HttpClient =新DefaultHttpClient();
字符串中的paramString = URLEn codedUtils.format(参数,可以UTF-8);
网址+ =? +中的paramString;
HTTPGET HTTPGET =新HTTPGET(URL); HTT presponse HTT presponse = httpClient.execute(HTTPGET);
HttpEntity httpEntity = HTT presponse.getEntity();
是= httpEntity.getContent();
} }赶上(UnsupportedEncodingException五){
e.printStackTrace();
}赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
} 尝试{
读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
是,ISO-8859-1),8);
StringBuilder的SB =新的StringBuilder();
串线= NULL;
而((行= reader.readLine())!= NULL){
sb.append(行+\\ n);
}
is.close();
JSON = sb.toString();
}赶上(例外五){
Log.e(缓冲区错误,错误转换结果+ e.toString());
} //尝试分析字符串到一个JSON对象
尝试{
jObj =新的JSONObject(JSON);
}赶上(JSONException E){
Log.e(JSON解析器,错误分析数据+ e.toString());
} //返回JSON字符串
返回jObj; }
}
我的活动,我要显示的数据是
包com.mahavega.qcdemo;
进口的java.util.ArrayList;
进口的java.util.List;进口com.mahavega.qcdemo.R;进口android.net.ConnectivityManager;
进口android.net.NetworkInfo;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.app.Activity;
进口android.app.AlertDialog;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.util.Log;
进口android.view.GestureDetector;
进口android.view.KeyEvent;
进口android.view.Menu;
进口android.view.MotionEvent;
进口android.view.View;
进口android.view.GestureDetector.SimpleOnGestureListener;
进口android.view.View.OnClickListener;
进口android.widget.ImageView;
进口android.widget.TextView;进口org.apache.http.NameValuePair;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;
公共类MainActivity扩展活动实现OnClickListener {
JSONParser jsonParser =新JSONParser();
私有静态最后弦乐url_product_detials =http://neogdgt.com/mob/get_det.php;
私有静态最后弦乐TAG_SUCCESS =成功;
私有静态最后弦乐TAG_EVENT =事件;
私有静态最后弦乐TAG_EVENTITLE =EVENT_TITLE;
私有静态最后弦乐TAG_EVENTDET =event_details; 私人GestureDetector gestureDetector;
View.OnTouchListener gestureListener;// Condetect CD =新Condetect(getApplicationContext());
//布尔isInternet present = cd.isConnectingToInternet();
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
gestureDetector =新GestureDetector(在此,新MyGestureDetector());
gestureListener =新View.OnTouchListener(){
公共布尔onTouch(视图V,MotionEvent事件){
返回gestureDetector.onTouchEvent(事件);
}
};
新GetEventDetails()执行();
ImageView的广告=(ImageView的)findViewById(R.id.imageView1);
ImageView的IM2 =(ImageView的)findViewById(R.id.imageView2);
ImageView的IM3 =(ImageView的)findViewById(R.id.imageView3);
ImageView的IM4 =(ImageView的)findViewById(R.id.imageView4);
ImageView的IM5 =(ImageView的)findViewById(R.id.imageView5);
ad.setOnClickListener(MainActivity.this);
im2.setOnTouchListener(gestureListener);
im2.setOnClickListener(MainActivity.this);
im3.setOnTouchListener(gestureListener);
im3.setOnClickListener(MainActivity.this);
im4.setOnTouchListener(gestureListener);
im4.setOnClickListener(MainActivity.this);
im5.setOnTouchListener(gestureListener);
im5.setOnClickListener(MainActivity.this);
ad.setOnClickListener(新OnClickListener(){ @覆盖
公共无效的onClick(视图v){
布尔INET = isOnline();
如果(INET)
{
startActivity(新意图(MainActivity.this,Adds.class));
overridePendingTransition(R.anim.slide_left,R.anim.slide_right);
完();
}
其他{
displayAlert();
}
}
});
} @覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
//充气菜单;如果是present这增加了项目操作栏。
。getMenuInflater()膨胀(R.menu.main,菜单);
返回true;
}
类MyGestureDetector扩展SimpleOnGestureListener {
@覆盖
公共布尔onFling(MotionEvent E1,E2 MotionEvent,浮velocityX,浮动velocityY)
{
浮sensitvity = 50;
如果((e1.getX() - e2.getX())≤; sensitvity){
startActivity(新意图(MainActivity.this,Login.class));
overridePendingTransition(R.anim.slide_right,R.anim.slide_left);
完();
}
否则如果((e2.getX() - e1.getX())> sensitvity){
startActivity(新意图(MainActivity.this,Login.class));
overridePendingTransition(R.anim.slide_right,R.anim.slide_left);
完(); } 返回super.onFling(E1,E2,velocityX,velocityY);
} }
@覆盖
公共无效的onClick(视图v){
// TODO自动生成方法存根
}
@覆盖
公共无效onBack pressed(){
完();
super.onBack pressed();
}
@覆盖
公共布尔的onkeydown(INT键code,KeyEvent的事件){
如果(键code == KeyEvent.KEY code_BACK
&功放;&安培; event.getRepeatCount()== 0){
onBack pressed();
} 返回true;
}
公共布尔isOnline(){
ConnectivityManager厘米=
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetInfo的的NetworkInfo = cm.getActiveNetworkInfo();
如果(NetInfo的= NULL&放大器;!&安培; netInfo.isConnectedOrConnecting()){
返回true;
}
返回false;
}
公共无效displayAlert()
{
新AlertDialog.Builder(本).setMessage(请检查您的Internet连接,然后重试)
.setTitle(网络错误)
.setCancelable(真)
.setNeutralButton(android.R.string.ok,
新DialogInterface.OnClickListener(){
公共无效的onClick(DialogInterface对话,诠释whichButton){
}
})
。显示();
}
类GetEventDetails扩展的AsyncTask<字符串,字符串,字符串> {
/ **
*获取产品的详细信息在后台线程
* * /
保护字符串doInBackground(字符串... PARAMS){ //从后台线程更新界面
runOnUiThread(新的Runnable(){
公共无效的run(){
//检查成功标记
诠释成功;
尝试{
//大厦参数
串的pid =1;
清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
params.add(新BasicNameValuePair(PID,PID)); //通过HTTP请求获得产品的详细信息
//注意产品的详细信息URL会使用GET请求
JSONObject的JSON = jsonParser.makeHtt prequest(
url_product_detials,GET,则params); //检查你的日志,JSON响应
Log.d(单一产品详细信息,json.toString()); // JSON的成功标签
成功= json.getInt(TAG_SUCCESS);
如果(成功== 1){
//成功接收产品的详细信息
JSONArray是eventObj = JSON
.getJSONArray(TAG_EVENT); // JSON数组 //从JSON数组的第一个产品对象
JSONObject的事件= eventObj.getJSONObject(0); //与本产品的PID发现
TextView的txtEventname =(的TextView)findViewById(R.id.textView2);
TextView的txtEventdet =(的TextView)findViewById(R.id.textView3);
//编辑文本
txtEventname.setText(event.getString(TAG_EVENTITLE));
txtEventdet.setText(event.getString(TAG_EVENTDET));
}其他{
//产品具有pid未找到
}
}赶上(JSONException E){
e.printStackTrace();
}
}
}); 返回null;
}
}
}
和我getdetails.php类
< PHP
//数组JSON响应
$响应=阵列();//其中包括DB连接类
require_once __DIR__。 /db_connect.php';//连接到数据库
$ DB =新DB_CONNECT();//检查数据后 //从产品表中的产品
$结果= mysql_query(SELECT * FROM tb_event_details WHERE事项标识= 1); 如果(!空($结果)){
//检查空结果
如果(mysql_num_rows($结果)大于0){ $结果= mysql_fetch_array($结果); $事件=阵列();
$事件[事项标识] = $结果[事项标识];
$事件[EVENT_TITLE] = $结果[EVENT_TITLE];
$事件[event_details] = $结果[event_details];
//成功
$响应[成功] = 1; //用户节点
$回应[事件] =阵列(); array_push($响应[事件],$事件); //呼应JSON响应
回声json_en code($响应);
}其他{
//没有产品找到
$响应[成功] = 0;
$响应[消息] =没有找到事件; //回声没有用户JSON
回声json_en code($响应);
}
}其他{
//没有产品找到
$响应[成功] = 0;
$响应[消息] =没有找到事件; //回声没有用户JSON
回声json_en code($响应);
}
?>
解决方案
只是添加
StrictMode.setThreadPolicy(新StrictMode.ThreadPolicy.Builder()
.detectDiskReads()。detectDiskWrites()。detectNetwork()
When I try to connect my app to MySQL database the application abruptly stops. I think the problem is with the jasonparsor class which I wrote. I need to accept the filed without posting any thing. how should I change my classes.. my JasonParsor is given below
package com.mahavega.qcdemo;
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() {
}
// function get json from url
// by making HTTP POST or GET method
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;
}
}
my activity which I want to display the data is
package com.mahavega.qcdemo;
import java.util.ArrayList;
import java.util.List;
import com.mahavega.qcdemo.R;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity implements OnClickListener {
JSONParser jsonParser = new JSONParser();
private static final String url_product_detials = "http://neogdgt.com/mob/get_det.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_EVENT = "event";
private static final String TAG_EVENTITLE = "event_title";
private static final String TAG_EVENTDET = "event_details";
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
// Condetect cd = new Condetect(getApplicationContext());
// Boolean isInternetPresent = cd.isConnectingToInternet();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gestureDetector = new GestureDetector(this, new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
new GetEventDetails().execute();
ImageView ad = (ImageView) findViewById(R.id.imageView1);
ImageView im2 = (ImageView) findViewById(R.id.imageView2);
ImageView im3 = (ImageView) findViewById(R.id.imageView3);
ImageView im4 = (ImageView) findViewById(R.id.imageView4);
ImageView im5 = (ImageView) findViewById(R.id.imageView5);
ad.setOnClickListener(MainActivity.this);
im2.setOnTouchListener(gestureListener);
im2.setOnClickListener(MainActivity.this);
im3.setOnTouchListener(gestureListener);
im3.setOnClickListener(MainActivity.this);
im4.setOnTouchListener(gestureListener);
im4.setOnClickListener(MainActivity.this);
im5.setOnTouchListener(gestureListener);
im5.setOnClickListener(MainActivity.this);
ad.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean inet = isOnline();
if (inet)
{
startActivity(new Intent(MainActivity.this, Adds.class));
overridePendingTransition(R.anim.slide_left, R.anim.slide_right);
finish();
}
else {
displayAlert();
}
}
});
}
@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;
}
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling (MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
float sensitvity = 50;
if((e1.getX() - e2.getX()) < sensitvity){
startActivity(new Intent(MainActivity.this, Login.class));
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
finish();
}
else if((e2.getX() - e1.getX()) > sensitvity){
startActivity(new Intent(MainActivity.this, Login.class));
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
finish(); }
return super.onFling(e1, e2, velocityX, velocityY);
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
@Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ( keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
onBackPressed();
}
return true;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public void displayAlert()
{
new AlertDialog.Builder(this).setMessage("Please Check Your Internet Connection and Try Again")
.setTitle("Network Error")
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
}
})
.show();
}
class GetEventDetails extends AsyncTask<String, String, String> {
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
String pid="1";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray eventObj = json
.getJSONArray(TAG_EVENT); // JSON Array
// get first product object from JSON Array
JSONObject event = eventObj.getJSONObject(0);
// product with this pid found
TextView txtEventname=(TextView) findViewById(R.id.textView2);
TextView txtEventdet=(TextView) findViewById(R.id.textView3);
// Edit Text
txtEventname.setText(event.getString(TAG_EVENTITLE));
txtEventdet.setText(event.getString(TAG_EVENTDET));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
}
}
and my getdetails.php class is
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
// get a product from products table
$result = mysql_query("SELECT *FROM tb_event_details WHERE event_id=1");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$events = array();
$events["event_id"] = $result["event_id"];
$events["event_title"] = $result["event_title"];
$events["event_details"] = $result["event_details"];
// success
$response["success"] = 1;
// user node
$response["events"] = array();
array_push($response["events"], $events);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No event found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No event found";
// echo no users JSON
echo json_encode($response);
}
?>
解决方案
just add
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
这篇关于Android的连接MySQL数据库...应用程序结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文