java - Android GUI 不显示

标签 java android xml user-interface

我目前正在为 Android 制作一个应用程序,但遇到一个问题,即我从主 Activity 开始的新 Activity 的 UI 没有显示。我不知道问题是什么。

这是我的第二个 Activity 的布局 xml 文件:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/TableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.tabcards.android.Search" >

<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" >

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
         >

        <TableLayout
            android:id="@+id/tableScrollView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:stretchColumns="yes"
            android:padding="5dp" 
            android:background="@color/gray">
        </TableLayout>
    </ScrollView>
</TableRow>

这是我的 Activity 代码:

public class Search extends ActionBarActivity {
TableLayout tableScrollView;
String[] JSONExceptions = { "type", "em", "user_id", "id", "profilepic", "bg"};
String value;
JSONObject jObject;

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

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        value = extras.getString("id");
    }
    System.out.println(value);
    tableScrollView = (TableLayout) findViewById(R.id.tableScrollView);
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {

                jObject = getJson("http://www.tabcards.com/req/androidapi/L2o30H8JlFMtFYHW3KLxkts20ztc5Be6Z6m6v315/json/"
                            + value);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    thread.start();
    try {
        thread.join();
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                createUI(jObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }               
        }

    });

    System.out.println("complete");

}

private void createUI(JSONObject jObject) throws JSONException {

    Iterator<?> keys = jObject.keys();
    int absIndex = 0;
    while( keys.hasNext() ){
        String key = (String)keys.next();
        if(!contains2(JSONExceptions , jObject.get(key))){
            String value = jObject.getString(key);
            System.out.println("level 1");
            if(value!="") {
                insertElement(key + " : " + value, absIndex++);

            }
        }
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.search, menu);
    return true;
}

private void insertElement(String data, int i) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View newRow = inflater.inflate(R.layout.row, null, false);
    newRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));

    TextView dataTextView = (TextView) newRow
            .findViewById(R.id.rowTextView);
    dataTextView.setText(data);
    System.out.println(dataTextView.getText().toString());
    tableScrollView.addView(newRow, i);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private InputStream downloadUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    return conn.getInputStream();
}

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public static JSONObject getJson(String url){

    InputStream is = null;
    String result = "";
    JSONObject jsonObject = null;

    // HTTP
    try {           
        HttpClient httpclient = new DefaultHttpClient(); // for port 80 requests!
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch(Exception e) {
        return null;
    }

    // Read response to string
    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");
            System.out.println(line);
        }
        is.close();
        result = sb.toString().replace("[", "");                
    } catch(Exception e) {
        return null;
    }

    // Convert string to object
    try {
        jsonObject = new JSONObject(result.replace("]", ""));            
    } catch(JSONException e) {
        return null;
    }

    return jsonObject;

}

这就是我创建 Activity 的方式:

Intent i = new Intent(getApplicationContext(), Search.class);
i.putExtra("id",searchEditText.getText().toString());
startActivity(i);

如果您需要更多信息,请告诉我。

最佳答案

问题:

thread.join();

这个问题是dreadlock,您正在等待thread执行完毕,这将使您的UI线程进入阻塞状态,例如Thread.Sleep() 因此,UI 线程正在等待您的请求执行完毕,然后才能在屏幕上显示布局。

来自documentation :

Like sleep, join responds to an interrupt by exiting with an InterruptedException.

解决方案:

仅使用一个线程,该线程仍将等待请求 (createUI) 并在之后执行您的 createUI 方法。

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        try {

            jObject = getJson("http://www.tabcards.com/req/androidapi/L2o30H8JlFMtFYHW3KLxkts20ztc5Be6Z6m6v315/json/"
                        + value);
            createUI(jObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});
thread.start();

关于java - Android GUI 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25467703/

相关文章:

android - GCM - 很少收到主题消息

Android、AsyncTask、长时间运行的进程和方向更改

java - 输入 validator 单元格编辑器

java - 将数组操作为新数组

java - java swing 中的标题分隔符

c# - 如何在不同的测试数据存储格式之间进行选择?

xml - PowerShell:如何将InnerText值连接为单个字符串?

java - 结果有问题

java - 在Android项目布局中添加Scrollview

xml - 将 Cobol 字帖转换为 XSD