0

I am trying to write an app that will connect to a database, extract data, and display that data on the phone. I am running into a problem though.

I connect to the database using:

try {           
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://74.208.131.62/Androidtest/testscript.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
    Log.d("Connection Success","Connected To Database");
} catch(Exception e) {

}

test.php is an sql which will return values: Item_ID(auto_inc_int), OtherTerms(String).

Then, I convert it to a string:

BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";

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

Then I use this part, which I don't understand, I just copied it from the internet:

int Item_id;
String Item_name;
String populate = new String();

try {       
    jArray = new JSONArray(result);
    JSONObject json_data = null;
    for(int i = 0; i < jArray.length(); i++) {
        json_data = jArray.getJSONObject(i);
        Item_id = json_data.getInt("id");
        Item_name = json_data.getString("item");
    }
...

However, I get the message "No Item found". I tried changing the name of the database, but I didn't get "Error in Connection" in LogCat, rather "No Item found".

I don't know if my app is successfully connecting to the database or not. I need to insert the result into a ListView object. What am I doing wrong?

(Also, happy holidays to you all!)

1 Answer 1

2

I am working on an app that does exactly what you are trying to do.

Heres my code:

this is the main activity. Here your connect to the php file and create an array from the JSON result.

public class mainActivity extends Activity {



@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);

    ArrayList<List> menuitems = getItems("android", 1); //Call to function to get results from web, you can put variables to pass here

    ListView listView = (ListView) findViewById(R.id.Menu);
    listView.setAdapter(new ListAdapter(this, R.layout.categorymenu, menuitems));

    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
          ON CLICK ACTIVITY GOES HERE




        }
    });
}

public ArrayList<List> getItems(String searchTerm, int page) {
    String searchUrl = "URL TO YOUR PHP FILE GOES HERE";

    ArrayList<List> lists = new ArrayList<List>();

    HttpClient client = new  DefaultHttpClient();
    HttpGet get = new HttpGet(searchUrl);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    String responseBody = null;
    try{
        responseBody = client.execute(get, responseHandler);
    }catch(Exception ex) {
        ex.printStackTrace();
    }

    JSONObject jsonObject = null;
    JSONParser parser=new JSONParser();

    try {
        Object obj = parser.parse(responseBody);
        jsonObject=(JSONObject)obj;

    }catch(Exception ex){
        Log.v("TEST","Exception: " + ex.getMessage());
    }

    JSONArray arr = null;

    try {
        Object j = jsonObject.get("results");
        arr = (JSONArray)j;
    }catch(Exception ex){
        Log.v("TEST","Exception: " + ex.getMessage());
    }

    for(Object t : arr) {
        List list = new List(
                ((JSONObject)t).get("categories_name").toString(),
                ((JSONObject)t).get("categories_id").toString()
                );
        lists.add(list);
    }

    return lists;


}   

/** Classes **/

public class List {
    public String name;
    public String message;
    public Boolean usernameSet = false;
    public Boolean messageSet = false;

    public List(String username, String message) {
        this.name = username;
        this.message = message;
    }
}

}

Then I use the menuListAdapater class to create the list view:

public class menuListAdapter extends ArrayAdapter<List> {
private ArrayList<List> lists;
    private Activity activity;


public menuListAdapter(Activity a, int textViewResourceId, ArrayList<List> lists) {
    super(a, textViewResourceId, lists);
    this.lists = lists;
    activity = a;

}

public static class ViewHolder{
    public TextView name;
    public TextView message;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    ViewHolder holder;
    if (v == null) {        
        LayoutInflater vi = 
            (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.categorymenu, null);
        holder = new ViewHolder();
        holder.name = (TextView) v.findViewById(R.id.categoryname);
        holder.message = (TextView) v.findViewById(R.id.message);
        v.setTag(holder);
    }
    else
        holder=(ViewHolder)v.getTag();

    final List list = lists.get(position);
    if (list != null) {
        holder.name.setText(list.name);
        holder.message.setText(list.message);
    }

    return v;
}

}

I highly recommend that you test the output of your php file in a browsers to make sure your queries and connection to the database work correctly.

Good Luck!

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

2 Comments

So, you mean without a listadapter I cannot accomplish this ? (I tried it only by using JsonObject.. Thank you so much for your reply! It helped alot!
I was trying understand the code you gave me. I have a small problem figuring out R.layout.catagorymenu. What is this object ? a listview?

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.