-1

次のような Android アプリケーションからこのファイルを呼び出していますが、アプリケーションがクラッシュします。

コードは次のとおりです。

    <?php
include("connection.php");
$src=$_POST['src'];
$dir=$_POST['tab'];
if($dir=="up")
    $tab="TRAINS";
else
    $tab="TRAIN";
$sql = "SELECT * FROM ".$tab." WHERE STATIONS LIKE '%".$src."%'";

//mysql_select_db($mysql_database);
$result = mysql_query($sql) 
or die(mysql_error());
$json = array();
while($row = mysql_fetch_array( $result ))     
{

    $bus = array(
        'id' => $row['_id'],
        'trainname' => $row['TRAINNAME'],
        'stations' => $row['STATIONS'],
        'arrival'=>$row['ARRIVAL']
    );
    array_push($json, $bus);
}

$jsonstring = json_encode($json);
echo $jsonstring;
//mysql_close($conn);
?>

Logcat ファイル:

    04-28 11:02:29.504: E/AndroidRuntime(8748): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobisys.android.External_to_application/com.mobisys.android.External_to_application.ListTrainsFromSrc}: java.lang.NullPointerException
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1728)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1747)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.ActivityThread.access$1500(ActivityThread.java:155)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:993)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.os.Handler.dispatchMessage(Handler.java:130)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.os.Looper.loop(SourceFile:351)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.ActivityThread.main(ActivityThread.java:3814)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at java.lang.reflect.Method.invokeNative(Native Method)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at java.lang.reflect.Method.invoke(Method.java:538)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:659)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at dalvik.system.NativeStart.main(Native Method)
04-28 11:02:29.504: E/AndroidRuntime(8748): Caused by: java.lang.NullPointerException
04-28 11:02:29.504: E/AndroidRuntime(8748):     at com.mobisys.android.External_to_application.ListTrainsFromSrc.onCreate(ListTrainsFromSrc.java:71)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1692)
04-28 11:02:29.504: E/AndroidRuntime(8748):     ... 11 more

PHP ファイルの呼び出し元のクラス: ListTrainsFrmSrc.java

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

//import com.mobisys.android.External_to_application.R;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class ListTrainsFromSrc extends Activity{
String res=null;
private static final String TAG_ID = "id";
private static final String TAG_TRAINNAME = "trainname";
private static final String TAG_STATIONS = "stations";
private static final String TAG_ARRIVAL = "arrival";
ArrayList<String> indexes=null;
ArrayList<String> Tables=null;
//String res=null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.single_list_item_view);
    String[] tabdata=null;
    Time dtNow = new Time();
    dtNow.setToNow();
    int hours = dtNow.hour;
    int minutes = dtNow.minute;
    int time=hours*100+minutes;
    ArrayList<String> indexes=new ArrayList<String>();
    ArrayList<String> Tables = new ArrayList<String>();
    Intent i = getIntent();
    // getting attached intent data
    String product = i.getStringExtra("Station");
    String dir=i.getStringExtra("Dir");
    String url="http://hotelmanagement.hostoi.com/dinesh/onlysrc.php"; 
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2); 
    nameValuePair.add(new BasicNameValuePair("src", product));
    nameValuePair.add(new BasicNameValuePair("tab",dir));

    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    final JSONArray json = jParser.getJSONFromUrl(url,nameValuePair);
    try{
    for(int p = 0; p < json.length(); p++){
        JSONObject jobj = json.getJSONObject(p);

        // Storing each json item in variable
        String id = jobj.getString(TAG_ID);
        String name = jobj.getString(TAG_TRAINNAME);
        String stations = jobj.getString(TAG_STATIONS);
        String arr = jobj.getString(TAG_ARRIVAL);

        String stn[]=stations.split(",");
        String arrt[]=arr.split(",");
        for(int j=0;j<stn.length;j++)
            {
                    if(stn[j].equals(product) && stn.length==arrt.length){
                        int start_time=Integer.parseInt(arrt[j]);
                        if(start_time>time){
                            indexes.add(id);
                            Tables.add(arrt[j]+"\t"+name);
                        }

                    break;
                }
            }
        }

        tabdata=Tables.toArray(new String[Tables.size()]);
        final int[] a = new int[indexes.size()];  
        int l = 0;  

        for (String integer : indexes)  
            a[l++] = Integer.parseInt(integer);  
        ListView listView1 = (ListView) findViewById(R.id.listView1);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, tabdata);
        listView1.setAdapter(adapter);

       listView1.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                    Intent i = new Intent(getApplicationContext(), ListTrainDetails.class);
                    i.putExtra("trainID",a[position]);
                    i.putExtra("json",json.toString());

                    startActivity(i);
                }
              });

    }catch(JSONException e) {
        e.printStackTrace();
    }
    }
}

JSONParser.java

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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONArray jArray = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url,List<NameValuePair> nvp) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(nvp));

            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 {
            jArray = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jArray;

    }
}
4

5 に答える 5

1

In PHP you concatenate strings with the dot (.) operator, not with the + operator

so this line:

$sql = "SELECT * FROM "+$tab+" WHERE STATIONS LIKE '%"+src+"%"+$dest+"%'" ;

should be like:

$sql = "SELECT * FROM ".$tab." WHERE STATIONS LIKE '%".src."%".$dest."%'" ;

Also, your code is vulnerable to SQL Injection.

Try to stay away from mysql_ functions, and use PDO or at least mysqli

于 2013-04-28T03:35:21.983 に答える
0

これを試して

$sql = "SELECT * FROM ".$tab." WHERE STATIONS LIKE '".src."%".$dest."%'" ;
于 2013-04-28T04:10:02.587 に答える
0

In PHP, . is used to concatenate strings, not +. Using + adds them as numbers, and in this case the result is 0. Therefore you are effectively running mysql_query("0"), which of course won't work.

于 2013-04-28T03:35:29.337 に答える
0

PHP での文字列連結は、 では.なくで行われ+ます。

$sql = "SELECT * FROM ".$tab." WHERE STATIONS LIKE '%".src."%".$dest."%'" ;
于 2013-04-28T03:35:35.407 に答える
0

php では、文字列を concat as として使用します。(ドット) 演算子、(+ 演算子) ではない

変化する

$sql = "SELECT * FROM "+$tab+" WHERE STATIONS LIKE '%"+src+"%"+$dest+"%'" ;

$sql = "SELECT * FROM ".$tab." WHERE STATIONS LIKE '%".$src."%".$dest."%'" ;
于 2013-04-28T03:38:01.177 に答える