0

I have these two activities in my Android application in which the first one is where the user will enter the asked information (to a edittext) and the other one is where it will send the data (I used putExtra to transfer the data from the 1st activity to the 2nd) to the MySQL database and will later on display results in ListView. The problem is, when the 2nd activity starts (considering that I have already entered something on the first activity) and after the progress dialog shows, there is nothing being displayed, or the results don't appear. But when I tried just starting the second activity (the edittext in the 1st activity is null) it shows the results. I'm not sure if what causes the problem, is on the application or in the PHP file I used in fetching the data?

Here are the codes:

MainActivity.java

//first activity
public class SearchFragment extends Fragment implements View.OnClickListener {

Button butt;
EditText destination;
String d;

public SearchFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.fragment_search, container, false);

    butt = (Button) view.findViewById(R.id.searchBUTTon);
    butt.setOnClickListener(this);

    destination = (EditText) view.findViewById(R.id.destinationTO);

    return view;
}

@Override
public void onClick(View v) {
    d = destination.getText().toString();
    Intent a = new Intent(getActivity(), SearchResultsActivity.class);
    a.putExtra("to", d);
    startActivity(a);

}
}

SearchResultsAcivity.java

//second activity
public class SearchResultsActivity extends AppCompatActivity implements ListView.OnItemClickListener {

private ListView listView;
private String JSON_STRING;

String destination;
TextView d;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_results);

    Intent a = getIntent();
    destination = a.getStringExtra("to");

    d = (TextView) findViewById(R.id.textView3);
    d.setText(destination);

    listView = (ListView) findViewById(R.id.listView);
    listView.setOnItemClickListener(this);

    getJSON();

}

private void showBusList() {

    JSONObject jsonObject = null;
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

    try {
        jsonObject = new JSONObject(JSON_STRING);
        JSONArray result = jsonObject.getJSONArray(config.TAG_JSON_ARRAY);

        for (int i = 0; i < result.length(); i++) {
            JSONObject jo = result.getJSONObject(i);

            //get strings
            String id = jo.getString(config.TAG_ID);
            String busName = jo.getString(config.TAG_BUSNAME);
            String terminal = jo.getString(config.TAG_TERMINAL);

            HashMap<String, String> busDetails = new HashMap<>();
            busDetails.put(config.TAG_ID, id);
            busDetails.put(config.TAG_BUSNAME, busName);
            busDetails.put(config.TAG_TERMINAL, terminal);
            list.add(busDetails);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    ListAdapter adapter = new SimpleAdapter(
            SearchResultsActivity.this, list, R.layout.result_list_item, new String[] {
            config.TAG_ID, config.TAG_BUSNAME, config.TAG_TERMINAL}, new int[] {R.id.id, R.id.busName,
            R.id.terminal});
    listView.setAdapter(adapter);


}

private void getJSON() {
    class GetJSON extends AsyncTask<Void, Void, String> {
        ProgressDialog loading;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            loading = ProgressDialog.show(SearchResultsActivity.this, "Message", "Fetching data... Please wait.", false, false);

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            JSON_STRING = s;
            showBusList();
        }

        @Override
        protected String doInBackground(Void... params) {

            RequestHandler rh = new RequestHandler();
            String s = rh.sendGetRequestParam(config.URL_SEARCH, destination);

            return s;

        }
    }

    GetJSON gj = new GetJSON();
    gj.execute();
}




@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

}

}

RequestHandler.java

//handles requests

public String sendGetRequestParam(String requestURL, String id){
    StringBuilder sb =new StringBuilder();
    try {
        URL url = new URL(requestURL+id);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

        String s;
        while((s=bufferedReader.readLine())!=null){
            sb.append(s+"\n");
        }
    }catch(Exception e){
    }
    return sb.toString();
}

PHP file

<?php
    $connection = mysqli_connect("mysql.hostinger.ph", "u679871488_bus", "Damnyoufudge20", "u679871488_bus") or die("Error " . mysqli_error($connection));

    $des = $_GET['destination'];

$sql = "SELECT * from appDB WHERE route LIKE  '%".$des."%'";
$result = mysqli_query($connection, $sql) or die ("Error in Selecting " . mysqli_error($connection));

$thisArray = array();
while($row = mysqli_fetch_assoc($result)) {
    $thisArray[] = $row;
}

echo json_encode(array('busDetails' => $thisArray));        

Error from logcat

03-06 16:10:25.525 31710-31710/com.thesis.iwander W/System.err: org.json.JSONException: Value <html> of type java.lang.String cannot be converted to JSONObject
 at org.json.JSON.typeMismatch(JSON.java:111)
 at org.json.JSONObject.<init>(JSONObject.java:159)
 at org.json.JSONObject.<init>(JSONObject.java:172)
 at com.thesis.iwander.SearchResultsActivity.showBusList(SearchResultsActivity.java:62)
 at com.thesis.iwander.SearchResultsActivity.access$100(SearchResultsActivity.java:29)
 at com.thesis.iwander.SearchResultsActivity$1GetJSON.onPostExecute(SearchResultsActivity.java:109)
 at com.thesis.iwander.SearchResultsActivity$1GetJSON.onPostExecute(SearchResultsActivity.java:93)
 at android.os.AsyncTask.finish(AsyncTask.java:632)
 at android.os.AsyncTask.access$600(AsyncTask.java:177)
 at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
 at android.os.Handler.dispatchMessage(Handler.java:110)
 at android.os.Looper.loop(Looper.java:193)
 at android.app.ActivityThread.main(ActivityThread.java:5333)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:515)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
 at dalvik.system.NativeStart.main(Native Method)
1
  • @MsYvette hi, I pasted the wrong PHP code (and just updated it). I think it has something to do with the LIKE clause I used in the php. So even when I entered nothing in the 1st activity, it will still show result from the db. Commented Mar 6, 2016 at 7:25

1 Answer 1

0

try array_push method in php in your php code

while($row = mysqli_fetch_assoc($result)) {
    //$thisArray[] = $row;
    array_push($thisArray, $row);
}

i think it'll work. Try it once and check if get this data in android.

It is bad practice to append user input directly to sql query in php like you used '%".$des."%'. It causes SQL Injection Attacks.

Always prefer mysqli_prepare($sql) to avoid SQL Injection Attacks.

UPDATE 1

In SearchResultsActivity.java, try to replace

destination = a.getStringExtra("to");

this line with

destination = a.getExtras().getString("to");
Log.e("tag", " DESTINATION :: " + destination);

And check if you're getting the text from first activity.

UPDATE 2

Never ever forget to catch exceptions you're throwing.

You forgot to catch exception in sendGetRequestParam method. Catch it and print it. So you'll know if there is any error connecting to server.

Sign up to request clarification or add additional context in comments.

10 Comments

Thank you for the response but the outcome is still the same. No results are displaying.
test your php code on browser if it works fine. also add ini_set('display_errors', 'On'); line in your php code to check if it throws any error.
the php in browser works fine, no errors whatsoever.
Then your android code has some issue. Please check if you had declared INTERNET permissions in Manifest file. Also check if your device is in same network with the server machine.
Yes. I already have INTERNET persmissions in my manifest file.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.