将android连接到mysql数据库...应用程序结束

时间:2013-04-28 03:55:26

标签: android mysql

当我尝试将我的应用程序连接到MySQL数据库时,应用程序突然停止。我认为问题在于我写的jasonparsor类。我需要接受该提交而不发布任何内容。我该怎么改变我的班级.. 我的JasonParsor在下面给出

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;

    }
}

我想要显示数据的活动是

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;
        }


}
}

我的getdetails.php类是

<?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);
    }
?>

1 个答案:

答案 0 :(得分:0)

只需添加

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
          .detectDiskReads().detectDiskWrites().detectNetwork()