简体   繁体   中英

Android program to GET values from server exits unexpectedly

I am making an android app that gets its data from a php script but it keeps on crashing.I have checked all the files that i have written and i cannot spot any error in it.Further more,it compiles with no errors.

This is my MainActivity.java

package com.whitehouse.sms;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

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

import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class MainActivity extends ListActivity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        String result = null;
        InputStream is = null;
        StringBuilder sb = null;
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        List<String> r = new ArrayList<String>();

        try{

        //http post
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://000.000.4.49/categories.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        }
        catch(Exception e){
            Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
       }

        //Convert response to string  
        try
        {
          BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));

          sb = new StringBuilder();

          String line = null;

          while ((line = reader.readLine()) != null) 
          {
             sb.append(line + "\n");
          }

          is.close();

          result = sb.toString();
        }
        catch(Exception e)
        {
            Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
        }
        //END Convert response to string   
        try{
                JSONArray jArray = new JSONArray(result);
                JSONObject json_data=null;
                for(int i=0;i<jArray.length();i++)
                {
                   json_data = jArray.getJSONObject(i);
                   r.add(json_data.getString("category"));
               }
               setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
            }
            catch(JSONException e1){
                Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
            } catch (ParseException e1) {
                Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
        }

    }
}

This is my android manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.whitehouse.sms"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-permission android:name="android.permission.INTERNET" />      
    <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
        <activity android:name=".Database_demo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>


</manifest> 

This is my main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>

and this is my strings.xml

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources>
    <string name="hello">Hello World, Database_demo!</string>
    <string name="app_name">Love Android Mobile Application</string>
</resources>

This is what i get from my php file

[{"category":"france"},{"category":"england"},{"category":"germany"},{"category":"denamrk"}]

and this is the php file

<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$sql=mysql_query("SELECT category from category");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>

Since everything looks fine,what could be wrong with the program?.

You are trying to run this from the main thread. Use async task.

      private class SendLocationHttpRequest extends AsyncTask<Object, Void, String> {
                        @Override
                        protected String doInBackground(Object... args) {
    try{

            //http post
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://000.000.4.49/categories.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            }
            catch(Exception e){
                Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
           }

            //Convert response to string  
            try
            {
              BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));

              sb = new StringBuilder();

              String line = null;

              while ((line = reader.readLine()) != null) 
              {
                 sb.append(line + "\n");
              }

              is.close();

              result = sb.toString();
            }
            catch(Exception e)
            {
                Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
            }
return some_data;
    }

                        @Override
                protected void onPostExecute(String result) {
                  //do later on stuff here
                }
            }

You can't use any Internet linked function in the main Thread which is reserved for the GUI. If you had read your LogCat, it should have been written.

Use an AsyncTask as gurinderhans suggest.

There is my MVC compatible code :

public class PHPRequestRetriever extends AsyncTask<Object, Void, String> {

    public interface Listener {
        void handlePHPRequestFinished(String result);
    }

    private Listener listener = null;
    private Exception exception = null;

    public PHPRequestRetriever(Listener listener) {
        this.listener = listener;
    }

    @Override
    protected String doInBackground(Object... params) {
        String data = "";
        String url = (String) params[0];
        ArrayList<NameValuePair> args = (ArrayList<NameValuePair>) params[1];
        InputStream is = null;

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(args));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("PHPRequestRetriever", "Error in http connection " + e.toString());
            exception = e;
        }

        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            data = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
            exception = e;
        }finally{
            is.close();
        }
        return data;
    }


    @Override
    protected void onPostExecute(String data) {
        if (exception == null && !data.equals("")) {
            this.listener.handlePHPRequestFinished(data);
        } else {
            Toast.makeText((Context) listener, "Error", Toast.LENGTH_LONG).show();
        }
    }
}

In your main Activity :

public class MainActivity extends ListActivity implements PHPRequestRetriever.Listener {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        PHPRequestRetriever retriever = new PHPRequestRetriever(this);
        ArrayList<NameValuePair> args = new ArrayList<NameValuePair>();
        // Set your args here
        retriever.execute("http://example.com/phpscript.php", args);

    }

    @Override
    public void handlePHPRequestFinished(String data) {
        // Handle the result
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM