【问题标题】:Layout with a button at start [closed]开始时带有按钮的布局[关闭]
【发布时间】:2014-09-11 12:39:22
【问题描述】:

我有这段代码。当我运行它时,它会从 JSON 中获取数据并显示。我想要一个 xml 布局,在我的应用程序开始时带有一个名为“新闻”的按钮,当您单击该“新闻”按钮时,我想显示我的 JSON 数据。如何使用按钮添加该布局?

http://www.megafileupload.com/en/file/551807/AdaDerana-rar.html

这是我的源代码。

这是我的 MainActivity 类

package com.example.adaderana;

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;



public class MainActivity extends Activity  {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;




    static String TITLE = "title";
    static String AUTHOR = "author";
    static String THUMBNAIL = "thumbnail";
    static String CONTENTS = "contents";
    static String IMAGE = "image";




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from list_main.xml
        setContentView(R.layout.listview_main);

        // Execute DownloadJSON AsyncTask
     new DownloadJSON().execute();

}
   // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {


 @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            // Set progressdialog title
            mProgressDialog.setTitle("Derana News");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }


        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions
                    .getJSONfromURL("http://www.adaderana.mobi/apple/ipad.php?q=topcat&cat=36");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("TopNewsGivenCat");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("title", jsonobject.getString("title"));
                    map.put("author", jsonobject.getString("author"));
                    map.put("thumbnail", jsonobject.getString("thumbnail"));
                    map.put("contents", jsonobject.getString("contents"));
                    map.put("image", jsonobject.getString("image"));

                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(MainActivity.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }
}

日志猫的最后一部分

07-21 03:58:03.110: I/Choreographer(1383): Skipped 31 frames!  The application may be doing too much work on its main thread.
07-21 03:58:04.110: I/MemoryCache(1383): MemoryCache will use up to 8.0MB
07-21 03:58:04.180: D/AndroidRuntime(1383): Shutting down VM
07-21 03:58:04.180: W/dalvikvm(1383): threadid=1: thread exiting with uncaught exception (group=0xb3a47b90)
07-21 03:58:04.200: E/AndroidRuntime(1383): FATAL EXCEPTION: main
07-21 03:58:04.200: E/AndroidRuntime(1383): Process: com.example.adaderana, PID: 1383
07-21 03:58:04.200: E/AndroidRuntime(1383): java.lang.NullPointerException
07-21 03:58:04.200: E/AndroidRuntime(1383):     at com.example.adaderana.MainActivity$DownloadJSON.onPostExecute(MainActivity.java:141)
07-21 03:58:04.200: E/AndroidRuntime(1383):     at com.example.adaderana.MainActivity$DownloadJSON.onPostExecute(MainActivity.java:1)
07-21 03:58:04.200: E/AndroidRuntime(1383):     at android.os.AsyncTask.finish(AsyncTask.java:632)
07-21 03:58:04.200: E/AndroidRuntime(1383):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-21 03:58:04.200: E/AndroidRuntime(1383):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
07-21 03:58:04.200: E/AndroidRuntime(1383):     at android.os.Handler.dispatchMessage(Handler.java:102)
07-21 03:58:04.200: E/AndroidRuntime(1383):     at android.os.Looper.loop(Looper.java:137)
07-21 03:58:04.200: E/AndroidRuntime(1383):     at android.app.ActivityThread.main(ActivityThread.java:4998)
07-21 03:58:04.200: E/AndroidRuntime(1383):     at java.lang.reflect.Method.invokeNative(Native Method)
07-21 03:58:04.200: E/AndroidRuntime(1383):     at java.lang.reflect.Method.invoke(Method.java:515)
07-21 03:58:04.200: E/AndroidRuntime(1383):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
07-21 03:58:04.200: E/AndroidRuntime(1383):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
07-21 03:58:04.200: E/AndroidRuntime(1383):     at dalvik.system.NativeStart.main(Native Method)
07-21 03:58:04.230: W/ActivityManager(371):   Force finishing activity com.example.adaderana/.MainActivity
07-21 03:58:04.270: D/gralloc(51): Registering a buffer in the process that created it. This may cause memory ordering problems.
07-21 03:58:04.270: E/libEGL(51): called unimplemented OpenGL ES API
07-21 03:58:04.280: E/libEGL(51): called unimplemented OpenGL ES API
07-21 03:58:04.280: E/libEGL(51): called unimplemented OpenGL ES API
07-21 03:58:04.280: E/libEGL(51): called unimplemented OpenGL ES API
07-21 03:58:04.280: E/SurfaceFlinger(51): glCheckFramebufferStatusOES error 1717000432
07-21 03:58:04.280: E/SurfaceFlinger(51): got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot
07-21 03:58:04.280: E/libEGL(51): called unimplemented OpenGL ES API
07-21 03:58:04.280: E/libEGL(51): called unimplemented OpenGL ES API
07-21 03:58:04.290: W/WindowManager(371): Screenshot failure taking screenshot for (246x410) to layer 21015
07-21 03:58:04.590: I/Choreographer(371): Skipped 44 frames!  The application may be doing too much work on its main thread.
07-21 03:58:04.960: W/ActivityManager(371): Activity pause timeout for ActivityRecord{b3fc7818 u0 com.example.adaderana/.MainActivity t8 f}
07-21 03:58:04.980: I/Choreographer(371): Skipped 39 frames!  The application may be doing too much work on its main thread.
07-21 03:58:05.310: I/Choreographer(371): Skipped 36 frames!  The application may be doing too much work on its main thread.
07-21 03:58:05.450: I/Choreographer(371): Skipped 35 frames!  The application may be doing too much work on its main thread.
07-21 03:58:05.620: I/Choreographer(371): Skipped 169 frames!  The application may be doing too much work on its main thread.
07-21 03:58:08.450: I/Choreographer(371): Skipped 40 frames!  The application may be doing too much work on its main thread.
07-21 03:58:08.790: I/Choreographer(371): Skipped 34 frames!  The application may be doing too much work on its main thread.
07-21 03:58:08.930: I/Choreographer(371): Skipped 36 frames!  The application may be doing too much work on its main thread.
07-21 03:58:09.060: I/Choreographer(371): Skipped 31 frames!  The application may be doing too much work on its main thread.
07-21 03:58:19.250: W/ActivityManager(371): Activity destroy timeout for ActivityRecord{b3fc7818 u0 com.example.adaderana/.MainActivity t8 f}

【问题讨论】:

  • 还是没有遇到你的问题,能详细说明一下吗?
  • 我按照 Aniruddha 说的做了。但我在 Intent i = new Intent (this, MainActivity.class);
  • @user3852473 尝试将this 替换为FirstActivity.this。它应该工作。如果对您有帮助,请勾选我的答案。

标签: java android json android-layout error-handling


【解决方案1】:

你们只是把new DownloadJSON().execute();放在你的新闻按钮onClick()里面:

Button b = (Button) findViewById(R.id.button1);

b.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        new DownloadJSON().execute();
    }
});

【讨论】:

  • 我确实喜欢..但应用程序突然关闭。它说不幸的是您的应用程序已关闭
  • 我也应该将我的 setContent 视图更改为有按钮的布局吗?
  • 我之前就是这么做的.. 但是出现错误 megafileupload.com/en/file/551807/AdaDerana-rar.html 你能检查一下吗?这是我的程序
  • 发布一些你的 logcat 信息。
  • 完成了。你能看看吗?
【解决方案2】:

将这些文件添加到您的项目中

activity_main.xml

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


<Button
         android:id="@+id/button1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Next" />

</LinearLayout>

FirstActivity.java

public class FirstActivity extends Activity {

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

    Button b = (Button) findViewById(R.id.button1);

b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent (FirstActivity.this, MainActivity.class);
            startActivity(i);
        }
    });
 }

}

你的 AndroidManifest.xml 应该是这样的

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your_package"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="your_package.FirstActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

     <activity android:name = ".MainActivity" > </activity>
    </application>

</manifest>

【讨论】:

  • 我应该在哪里添加 imageview id?
  • 我在 Intent i = new Intent (this, MainActivity.class) 处收到错误;构造函数 Intent(new View.OnClickListener(){}, Class) 未定义
  • 已经导入了
  • 发布您在问题中所做的任何更改。让我看看。尝试将this 替换为FirstActivity.this。它应该工作。检查我编辑的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
  • 2011-02-26
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
相关资源
最近更新 更多