尝试在Android应用程序中使用Toast时出错

时间:2015-11-14 10:45:47

标签: android android-layout android-activity

在我的应用程序中,我从在线服务器获取json数据。之后我试图通过吐司显示数据。但应用程序停止工作。如果我评论吐司部分,那么应用程序运行顺利。所以我觉得吐司部分有问题。所以伙计们帮助我找出问题的原因

   package com.example.getdata;

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

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.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;





import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;

public class MainActivity extends Activity {

    EditText password,username;
    String pass,user;
    //TextView output;

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

    }


    public void onConnect(View v) {




         new Thread(){
             public void run(){
                 HttpClient myClient = new DefaultHttpClient();
                 HttpPost post = new HttpPost("http://tusharinfotech.com/debasish/get_data.php");
             try {
                     List<NameValuePair> myArgs = new ArrayList<NameValuePair>();
                    // myArgs.add(new BasicNameValuePair("username", user));
                    // myArgs.add(new BasicNameValuePair("password", pass));
                     post.setEntity(new UrlEncodedFormEntity(myArgs));
                     HttpResponse myResponse = myClient.execute(post);
                     BufferedReader br = new BufferedReader( new InputStreamReader(myResponse.getEntity().getContent()));
                     String line = "";
                     String data1 ="";
                     while ((line = br.readLine()) != null)
                     {
                         try {
                            JSONArray myarray = new JSONArray(line);
                            for(int i=0;i<myarray.length();i++){
                                JSONObject jsonObject = myarray.getJSONObject(i); 
                                int id = Integer.parseInt(jsonObject.optString("FOOD_ID").toString());
                                String name = jsonObject.optString("FOOD_NAME").toString();
                                data1 += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n ";  
                            }

                        //Log.d("mytag",data);
                            //this application stop working for this toast part.. if i commented it then the application run smoothly
                            Toast.makeText(getApplicationContext(),data1, Toast.LENGTH_LONG).show();
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                         //EditText output1 = (EditText) findViewById(R.id.editText1);
                        // output1.setText(data);
                         Log.d("mytag", line);

                     }
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
             }
         }.start();

     }



}

3 个答案:

答案 0 :(得分:5)

我猜你试图在后台线程上显示吐司,这在android中是不允许的。您可以使用此代码在后台线程中显示吐司:

$('.someClick').click(function(e){
   e.preventDefault();
   x.modal('show');
   x.on('shown.bs.modal', function(){
       x.find('.modal-body').load('path/page.html', function(response, status, xhr){
           if(status == "success"){
               $("select[name=elementName]").chosen({ width:'100%' }); /* add width here !!! */
           }
       });
   });
});

答案 1 :(得分:0)

您必须仅显示来自UI线程的Toast,要解决此问题,您可以使用runOnUiThread()方法或创建新的Handler并传入构造函数Looper.getMainLoopper()

答案 2 :(得分:0)

您可以使用AsyncTask Framework更轻松地进行后台处理http://developer.android.com/reference/android/os/AsyncTask.html。 方法onPostExecute(Result)将在您的UI线程上运行,您可以在此处更改UI元素。