将应用程序连接到WebServer并从MYSQL Server中提取信息

时间:2013-11-08 11:41:02

标签: java android mysql xml json

我目前正在为我的网站构建一个Android应用程序http://loadedgeek.com - 如果你访问它,它是一个论坛,所以我希望应用程序允许用户创建/发布主题,阅读主题,并注册通过应用程序的站点没有应用程序打开浏览器。

现在我希望用户在点击“查看主题”时希望它通过其数据库在网站上显示主题,因此MainActivity调用AllTopicsActivity。这是我有问题的地方,我仍然是一个学习者,所以我在谷歌搜索并将代码组合在一起,活动让用户编辑主题而不只是阅读主题。

这是main.xml文件

  

<!--  Sample Dashboard screen with four buttons -->
<!--  Button to view all topics screen -->
<Button android:id="@+id/btnViewTopics"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="View Topics"
    android:layout_marginTop="25dip"/>

<!--  Button to create a new topic screen -->
<Button android:id="@+id/btnCreateTopics"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Add New Topic"
    android:layout_marginTop="25dip"/>

<!-- Button to create a loadedgeek account -->    <Button android:id="@+id/btnCreateAccount"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Create An Account"
    android:layout_marginTop="25dip"/>
      <!-- Button To Check For Updates -->    <Button android:id="@+id/btnCheckForUpdate"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Check For Application Update"
    android:layout_marginTop="25dip"/>
      <!-- Button To View Application Information -->     <Button android:id="@+id/btnViewAppDetails"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="About The Application"
    android:layout_marginTop="25dip"/>   </LinearLayout>

当用户单击View Topic Button时,这是调用AllTopicsActivity的MainActivity

  

package com.loadedgeek.app; import android.app.Activity;进口   android.content.Intent; import android.os.Bundle;进口   android.view.View; import android.widget.Button;公共课   MainActivity扩展了Activity {

Button btnViewTopics;
Button btnNewTopic;   Button btnCreateAccount;    Button btnCheckForUpdates;  Button btnViewAppDetails

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

    // Buttons
    btnViewTopics = (Button) findViewById(R.id.btnViewTopics);
    btnNewTopic = (Button) findViewById(R.id.btnCreateTopic);         btnCreateAccount = (Button) findViewById(R.id.btnCreateAccount);
  btnCheckForUpdates = (Button) findViewById(R.id.btnCheckForUpdates);
  btnViewAppDetails = (Button) findViewById(R.id.btnViewAppDetails);

    // view topics click event
    btnViewTopics.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // Launching All topics Activity
            Intent i = new Intent(getApplicationContext(), AllTopicsActivity.class);
            startActivity(i);

        }
    });

    // new topic click event
    btnNewTopic.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // Launching create new topic activity
            Intent i = new Intent(getApplicationContext(), NewTopicActivity.class);
            startActivity(i);

        }
    });
          // create account click event
    btnCreateAccount.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // Launching All topics Activity
            Intent i = new Intent(getApplicationContext(), CreateAccount.class);
            startActivity(i);

        }
    });
          // check for updates click event
    btnCheckForUpdates.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // Launching All topics Activity
            Intent i = new Intent(getApplicationContext(), CheckUpdates.class);
            startActivity(i);

        }
    });
          // view app click event
    btnViewAppDetails.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // Launching All topics Activity
            Intent i = new Intent(getApplicationContext(), AppDetails.class);
            startActivity(i);

        }
    });
} }

现在这是我遇到问题的AllTopicActivity

  

package com.loadedgeek.official; import java.util.ArrayList;进口   的java.util.HashMap; import java.util.List;进口   org.apache.http.NameValuePair; import org.json.JSONArray;进口   org.json.JSONException; import org.json.JSONObject;进口   android.app.ListActivity; import android.app.ProgressDialog;进口   android.content.Intent; import android.os.AsyncTask;进口   android.os.Bundle; import android.util.Log; import android.view.View;   import android.widget.AdapterView;进口   android.widget.AdapterView.OnItemClickListener;进口   android.widget.ListAdapter; import android.widget.ListView;进口   android.widget.SimpleAdapter; import android.widget.TextView;上市   class AllTopicsActivity扩展了ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> topicsList;

// url to get all products list
private static String url_all_topics = "http://api.loadedgeek.com/android_connect/get_all_topics.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_TOPIC = "topic";
private static final String TAG_ID = "id";
private static final String TAG_SUBJECT = "subject";

// products JSONArray
JSONArray products = null;

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

    // Hashmap for ListView
    topicsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllTopics().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit topic
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String id = ((TextView) view.findViewById(R.id.id)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    EditTopicActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_ID, id);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

}

当用户点击主题而不是文本视图时,您会发现它是一个EditTopicActivity :(

它在列表视图中显示主题,但当用户点击任何主题时,它将显示并让用户编辑我不想要的主题,我尝试删除编辑代码,但它分散整个项目,所以正确现在我需要帮助,我希望活动在文本视图中显示主题及其详细信息,而无需用户编辑或删除它..谢谢

这是EditTopicActivity,它包含删除和更新我想要避免和删除的主题的活动..它还显示edit_topic.xml文件。活动belo

  

公共类EditTopicActivity扩展了Activity {

EditText txtSubject;
EditText txtPoster;
EditText txtMessage;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;

String pid;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

// single product url
private static final String url_topic_detials = "http://api.loadedgeek.com/android_connect/get_topic_details.php";

// url to update product
private static final String url_update_topic = "http://api.loadedgeek.com/android_connect/update_topic.php";

// url to delete product
private static final String url_delete_topic = "http://api.loadedgeek.com/android_connect/delete_topic.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_TOPIC = "topic";
private static final String TAG_ID = "id";
private static final String TAG_SUBJECT = "subject";
private static final String TAG_POSTER = "poster";
private static final String TAG_MESSAGE = "message";

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

    // save button
    btnSave = (Button) findViewById(R.id.btnSave);
    btnDelete = (Button) findViewById(R.id.btnDelete);

    // getting product details from intent
    Intent i = getIntent();

    // getting product id (pid) from intent
    pid = i.getStringExtra(TAG_ID);

    // Getting complete product details in background thread
    new GetProductDetails().execute();

    // save button click event
    btnSave.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // starting background task to update product
            new SaveTopicDetails().execute();
        }
    });

    // Delete button click event
    btnDelete.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // deleting product in background thread
            new DeleteTopic().execute();
        }
    });

}

/**
 * Background Async Task to Get complete product details
 * */
class GetProductDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditTopicActivity.this);
        pDialog.setMessage("Loading Topic details. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * 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
                    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_topic_detials, "GET", params);

                    // check your log for json response
                    Log.d("Single Topic Details", json.toString());

                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // successfully received product details
                        JSONArray topicsObj = json
                                .getJSONArray(TAG_TOPICS); // JSON Array

                        // get first product object from JSON Array
                        JSONObject topics = topicsObj.getJSONObject(0);

                        // product with this pid found
                        // Edit Text
                        txtSubject = (EditText) findViewById(R.id.inputSubject);
                        txtPoster = (EditText) findViewById(R.id.inputPoster);
                        txtMessage = (EditText) findViewById(R.id.inputMessage);

                        // display product data in EditText
                        txtSubject.setText(topics.getString(TAG_SUBJECT));
                        txtPoster.setText(topics.getString(TAG_POSTER));
                        txtMessage.setText(topics.getString(TAG_MESSAGE));

                    }else{
                        // product with pid not found
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
    }
}

/**
 * Background Async Task to  Save product Details
 * */
class SaveTopicDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditTopicActivity.this);
        pDialog.setMessage("Saving Topic ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Saving product
     * */
    protected String doInBackground(String... args) {

        // getting updated data from EditTexts
        String name = txtName.getText().toString();
        String price = txtPrice.getText().toString();
        String description = txtDesc.getText().toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(TAG_PID, pid));
        params.add(new BasicNameValuePair(TAG_NAME, name));
        params.add(new BasicNameValuePair(TAG_PRICE, price));
        params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));

        // sending modified data through http request
        // Notice that update product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_update_product,
                "POST", params);

        // check json success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully updated
                Intent i = getIntent();
                // send result code 100 to notify about product update
                setResult(100, i);
                finish();
            } else {
                // failed to update product
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product uupdated
        pDialog.dismiss();
    }
}

/*****************************************************************
 * Background Async Task to Delete Product
 * */
class DeleteProduct extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditTopicActivity.this);
        pDialog.setMessage("Deleting Topic...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Deleting product
     * */
    protected String doInBackground(String... args) {

        // Check for success tag
        int success;
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("id", id));

            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                    url_delete_product, "POST", params);

            // check your log for json response
            Log.d("Delete Topic", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // product successfully deleted
                // notify previous activity by sending code 100
                Intent i = getIntent();
                // send result code 100 to notify about product deletion
                setResult(100, i);
                finish();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();

    }

} }

唉,edit_topic文件

  

      

<!-- Input Name -->
<EditText android:id="@+id/inputSubject"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dip"
    android:layout_marginBottom="15dip"
    android:singleLine="true"/>

<!-- Price Label -->
<TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Your Name"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="10dip"
    android:textSize="17dip"/>

<!-- Input poster name -->
<EditText android:id="@+id/inputPoster"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dip"
    android:layout_marginBottom="15dip"
    android:singleLine="true"/>

<!-- Description Label -->
<TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Topic Message"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="10dip"
    android:textSize="17dip"/>

<!-- Input description -->
<EditText android:id="@+id/inputMessage"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dip"
    android:layout_marginBottom="15dip"
    android:lines="4"
    android:gravity="top"/>

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <!-- Button Csave topic -->
<Button android:id="@+id/btnSave"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Save Changes"
    android:layout_weight="1"/>

<!-- Button Create topic -->
<Button android:id="@+id/btnDelete"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Delete"
    android:layout_weight="1"/>
</LinearLayout>   </LinearLayout>

0 个答案:

没有答案