【问题标题】:How to set the textview if condition is satisfied?如果满足条件,如何设置文本视图?
【发布时间】:2014-11-22 11:16:24
【问题描述】:

在我之前的问题How to Print Message when Json Response has no fileds? Toast 工作正常,但如果我的回复显示没有包含数组的文件,如果我想使用 textview 而不是 Toast,该怎么办?谁能帮帮我?

public class MessageSent extends ListActivity{

    private ProgressDialog pDialog;
    JSONArray msg=null;
    private TextView nomsg;

    private ListView listview;

    private ArrayList<HashMap<String,String>> aList;
    private static String MESSAGE_URL = "";
    private static final String MESSAGE_ALL="msg";
    private static final String MESSAGEUSER_ID="msg_user_id";
    private static final String MESSAGE_NAME="name";
    private static final String MESSAGE_PROFILE="profile_id";
    private static final String MESSAGE_IMAGE="image";
    private static final String MESSAGE_CAST="cast";
    private static final String MESSAGE_AGE="age";
    private static final String MESSAGE_LOCATION="location";
    private CustomAdapterMessage adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_view_msgsent);
        nomsg=(TextView)findViewById(R.id.no_message);
        String strtexts = getIntent().getStringExtra("id");
        System.out.println("<<<<<<<< id : " + strtexts);
        MESSAGE_URL = "xxxxx"+strtexts;

        // listview=(ListView)findViewById(R.id.list);

        //ListView listview = this.getListView();

        ListView listview = (ListView)findViewById(android.R.id.list);

        new LoadAlbums().execute();


            }
        });
    }

    class LoadAlbums extends AsyncTask>> {

        /**
         * Before starting background thread Show Progress Dialog
         * */

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MessageSent.this);
            pDialog.setMessage("Loading...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
            String jsonStr = sh.makeServiceCall(MESSAGE_URL, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) 
            {
                try 
                {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    msg = jsonObj.getJSONArray(MESSAGE_ALL);

                    // looping through All Contacts
                    for (int i = 0; i < msg.length(); i++) 
                    {
                        JSONObject c = msg.getJSONObject(i);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(MESSAGEUSER_ID ,c.getString(MESSAGEUSER_ID));
                        map.put(MESSAGE_NAME,c.getString(MESSAGE_NAME));
                        map.put(MESSAGE_PROFILE, c.getString(MESSAGE_PROFILE));
                        map.put(MESSAGE_IMAGE, c.getString(MESSAGE_IMAGE));
                        map.put(MESSAGE_CAST, c.getString(MESSAGE_CAST));
                        map.put(MESSAGE_AGE, c.getString(MESSAGE_AGE)+" years");
                        map.put(MESSAGE_LOCATION, c.getString(MESSAGE_LOCATION));

                        // adding HashList to ArrayList
                        data.add(map);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return data;
        }

        protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
            super.onPostExecute(result);

            // dismiss the dialog after getting all albums
            if (pDialog.isShowing())
                pDialog.dismiss();

            if(msg == null || msg.length() == 0) { 
                //Toast.makeText(getApplicationContext(), "No response", Toast.LENGTH_LONG).show
                nomsg.setText("No Message Found");
                //nomsg.setBackgroundDrawable(R.drawable.borders);
            }

            if(aList == null) {
                aList = new ArrayList<HashMap<String, String>>();
                aList.addAll(result);
                adapter = new CustomAdapterMessage(getBaseContext(), result);
                setListAdapter(adapter);
            } else {
                aList.addAll(result);
                adapter.notifyDataSetChanged();
            }
        }

    }
}

【问题讨论】:

  • 你能把你的代码放上去吗
  • 关注我之前的问题

标签: android textview


【解决方案1】:

您在设置应用程序时似乎有些困惑。让我解释一些事情,并提供一些示例代码。

AsynTask 的使用?

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

但是在后台线程中工作时,您必须在 UI 中执行一些操作。在这种情况下,您可以使用,

1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

2. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

在您的特定情况下,您要在操作后设置值,您必须使用 AsynTask 的后一种方法。

引用您遵循的示例的相同代码,

//MainActivity.java
public class MainActivity extends ListActivity {

    TextView yourTextView;

     @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        .
        .
        //change the ID in this line from what you are using
        yourTextView = (TextView) findViewByID(R.id.id_in_activity_main);
        .
        .

        // Calling async task to get json
        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            .
            .
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            .
            .
        }

        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (pDialog.isShowing())
                pDialog.dismiss();

            if(contacts == null || contacts.length() <= 0){
                yourTextView.setText("No Data");   
            }
         }
     }
 }

【讨论】:

  • 我很喜欢这个答案,我和你说的一样,但是我的应用程序崩溃了
  • 能否请您使用您的代码和 logcat 更新问题。这将有助于轻松识别问题
  • 如果以上都正确,然后选择你的项目Project -&gt; Clean,然后尝试运行你的项目。有时链接可能会出现问题。
【解决方案2】:

试试这个方法:

protected void onPostExecute(Void result) {
    super.onPostExecute(result);

    if (pDialog.isShowing())
        pDialog.dismiss();

    if(contacts == null || contacts.length() <= 0){
        yourTextView.setText("No Data");   
    }
 }

【讨论】:

  • 我做了,但它让我的应用崩溃了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-06
  • 2018-11-29
  • 1970-01-01
  • 2014-06-22
  • 2021-11-11
  • 2021-09-28
相关资源
最近更新 更多