如何从数据库中检索数据并在textview中显示为android? Asynctask不加载我的数据?

时间:2021-08-15 19:32:15

How do you display value from a database and display it in textview in android. I have got a tutorial for json parser and it seems to be working fine. When the application is running, it does not load my activity to the textview and it also does not show my status. I have posted yesterday for fault exception and I was helped. The activity seems to be never load my data into textview. I am posting up my code.

如何显示数据库中的值并在android中的textview中显示它。我有一个json解析器的教程,它似乎工作正常。当应用程序运行时,它不会将我的活动加载到textview,也不会显示我的状态。我昨天发布了故障异常,我得到了帮助。该活动似乎永远不会将我的数据加载到textview中。我正在发布我的代码。

Here is my json. That I want to parse. It seems that I am parsing it correctly. But not displaying correctly.

这是我的json。我要解析。好像我正在解析它。但没有正确显示。

{"success":1,"message":"Retrieve Status Successful!","status":[{"lock_op":"0","door_op":"0","date_modified":"2015-05-08 09:56:35"}]} 

Here is the status activity

这是状态活动

package com.locking;

import android.support.v7.app.ActionBarActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import org.json.simple.*;
import org.json.simple.parser.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import com.locking.libraries.LobbyFunctions;
import com.locking.libraries.UserFunctions;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;

public class StatActivity extends Activity {
    int userId;
    int temp;
    int lockset = 0;
    int templock;
    int doorset = 0;
    String lock_op;
    String door_op;
    String door;
    String lock;
    String date;

    JSONArray status_user = null;
    TextView lockstat;
    TextView DoorStat;
    TextView DateStat;
    String statdisplay = "Lock is open";
    String statdisplay2 = "Lock is closed";
    String doordisplay = "door is open";
    String doordisplay2 = "door is closed";

//ArrayList<HashMap<String, String>> statusList;

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_STATUS = "status";
    private static final String TAG_LOCK = "lock_op";
    private static final String TAG_DOOR = "door_op";
    private static final String TAG_DATE = "date_modified";

    private ProgressDialog pDialog;


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

        //statusList = new ArrayList<HashMap<String, String>>();


        lockstat = (TextView) findViewById(R.id.switchstat);
        DoorStat = (TextView) findViewById(R.id.textView1);
        DateStat = (TextView) findViewById(R.id.DateField);

        try {

            // get lobbies from JSON and parse them. Wait until async task is
            // complete before continuing
            new GetStats().execute().get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    class GetStats extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(StatActivity.this);
            pDialog.setMessage("Fetching Status..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... args) {

            try {
                LobbyFunctions lobbyFunction = new LobbyFunctions();
                JSONObject json3 = lobbyFunction.GetStatus();
                int success = json3.getInt(TAG_SUCCESS);
                String message = json3.getString(TAG_MESSAGE);
                String status = json3.getString(TAG_STATUS);
                JSONArray status_user = new JSONArray(status);
                JSONObject c = status_user.getJSONObject(0);

                lock =c.getString(TAG_LOCK);
                door =c.getString(TAG_DOOR);
                date =c.getString(TAG_DATE);

                if (lock.equals("0")) {
                    lock = statdisplay;
                }
                if (lock.equals("1")) {
                    lock = statdisplay2;
                }

                if (door.equals("0")) {
                    door = doordisplay;
                }
                if (door.equals("1")) {
                    door = doordisplay2;
                }
                /*
                HashMap<String, String> statlist = new HashMap<String, String>();
                statlist.put(TAG_LOCK, lock);
                statlist.put(TAG_DOOR, door);
                statlist.put(TAG_DATE, date);

                statusList.add(statlist);

                */

            } catch (JSONException e) {
                e.printStackTrace();
            }

            // TODO Auto-generated method stub
            return null;
        }
        protected void onPostExecute(Void result) {
            // dismiss the dialog once done
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                public void run() {
                    Log.d("am I getting anything", lock);
                    lockstat.setText(lock);
                    DoorStat.setText(door);
                    DateStat.setText(date);

                }
            });


        }


    }

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

}

Here is my main activity.

这是我的主要活动。

package com.locking;

import android.support.v7.app.ActionBarActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import org.json.simple.*;
import org.json.simple.parser.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import com.locking.libraries.LobbyFunctions;
import com.locking.libraries.UserFunctions;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;



   public class MainActivity extends Activity {
        int userId;
        int temp;
        int lockset = 0;
        int templock;
        int doorset = 0;
        String lock_op;
        String door_op;
        String str_lockSet;
        String str_lockOff;

        JSONArray status_user = null;
        TextView lockstat;
        TextView DoorStat;
        TextView DateStat;
        String statdisplay = "Lock is open";
        String statdisplay2 = "Lock is closed";
        String doordisplay = "door is open";
        String doordisplay2 = "door is closed";

        private static final String TAG_SUCCESS = "success";
        private static final String TAG_MESSAGE = "message";

        private ProgressDialog pDialog;

        LobbyFunctions lobbyFunction = new LobbyFunctions();
        UserFunctions userFunction = new UserFunctions();
        UserFunctions socketConnect = new UserFunctions();
        UserFunctions sktConnect = new UserFunctions();

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

            Intent extras = getIntent();
            lockset = extras.getIntExtra("lockset", 0);
            doorset = extras.getIntExtra("doorset", 0);
            // userId = extras.getIntExtra("userId", 0);
            // temp = extras.getIntExtra("temp", 0);

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

            Button lock_on = (Button) findViewById(R.id.lock_on);
            Button lock_off = (Button) findViewById(R.id.lock_off);
            // button click event
            lock_on.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    new PostStatusOn().execute();
                    Intent restart = new Intent(getApplicationContext(),
                            MainActivity.class);
                    startActivity(restart);
                    finish();
                }
            });
            lock_off.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    // creating new product in background thread
                    new PostStatusOff().execute();
                    Intent restart = new Intent(getApplicationContext(),
                            MainActivity.class);
                    startActivity(restart);
                    finish();
                }
            });
            check.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // creating new product in background thread
                    Intent gotocheck = new Intent(getApplicationContext(),
                            StatActivity.class);
                    startActivity(gotocheck);
                    finish();
                }
            });

        }

        class PostStatusOn extends AsyncTask<String, String, String> {

            protected String doInBackground(String... args) {
                if (lockset == 1) {
                    str_lockSet = "1";
                } else {
                    str_lockSet = "1";
                }
                // String str_lockSet = Integer.toString(lockset);
                String str_doorSetS = Integer.toString(doorset);

                JSONObject json = userFunction
                        .sendStatus(str_lockSet, str_doorSetS);
                // JSONObject jsonMod = userFunction.sendStatusMod(str_lockSet,
                // str_doorSetS);
                socketConnect.sendStatusMod(str_lockSet, str_doorSetS);
                Log.d("Create Response", json.toString());

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

                    if (success == 1) {
                        // successfully registered the user
                        Log.d("User Registered!", json.toString());
                        Intent Logon = new Intent(getApplicationContext(),
                                MainActivity.class);
                        startActivity(Logon);

                        // closing this screen
                        finish();
                        return json.getString(TAG_MESSAGE);
                    } else {

                        // failed to register the user
                        Log.d("Register Failure!", json.getString(TAG_MESSAGE));
                        return json.getString(TAG_MESSAGE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return null;

            }
        }

        class PostStatusOff extends AsyncTask<String, String, String> {
            protected String doInBackground(String... args) {
                if (lockset == 1) {
                    str_lockOff = "0";
                } else {
                    str_lockOff = "0";
                }

                // String str_lockOff = Integer.toString(lockOff);
                String str_doorSetS = Integer.toString(doorset);

                JSONObject json2 = userFunction.sendStatus(str_lockOff,
                        str_doorSetS);
                sktConnect.sendStatusMod(str_lockOff, str_doorSetS);

                Log.d("Create Response", json2.toString());

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

                    if (success == 1) {
                        // successfully registered the user
                        Log.d("Status Posted!", json2.toString());
                        Intent Logon = new Intent(getApplicationContext(),
                                MainActivity.class);
                        startActivity(Logon);

                        // closing this screen
                        finish();
                        return json2.getString(TAG_MESSAGE);
                    } else {

                        // failed to register the user
                        Log.d("Register Failure!", json2.getString(TAG_MESSAGE));
                        return json2.getString(TAG_MESSAGE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return null;

            }
        }








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

        }

Here is my manifest file. I am sure that the manifest and my main activity is correct.

这是我的清单文件。我确信清单和我的主要活动是正确的。

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

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".RegisterActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan" />
        <activity
            android:name=".StatActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan" />
    </application>
</manifest>

Please help me to solve this problem.

请帮我解决这个问题。

Here is my new error now.

这是我现在的新错误。

05-08 16:07:19.001: E/AndroidRuntime(1866): FATAL EXCEPTION: main
05-08 16:07:19.001: E/AndroidRuntime(1866): Process: com.locking, PID: 1866
05-08 16:07:19.001: E/AndroidRuntime(1866): java.lang.NullPointerException
05-08 16:07:19.001: E/AndroidRuntime(1866):     at com.locking.StatActivity$GetStats$1.run(StatActivity.java:159)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at android.app.Activity.runOnUiThread(Activity.java:4713)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at com.locking.StatActivity$GetStats.onPostExecute(StatActivity.java:156)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at com.locking.StatActivity$GetStats.onPostExecute(StatActivity.java:1)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at android.os.AsyncTask.finish(AsyncTask.java:632)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at android.os.Handler.dispatchMessage(Handler.java:102)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at android.os.Looper.loop(Looper.java:136)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at android.app.ActivityThread.main(ActivityThread.java:5017)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at java.lang.reflect.Method.invokeNative(Native Method)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at java.lang.reflect.Method.invoke(Method.java:515)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-08 16:07:19.001: E/AndroidRuntime(1866):     at dalvik.system.NativeStart.main(Native Method)

Updated Error with logcat saying my lock is closed. Meaning my lock_op is 1 from database. And I am able to retrieve the value. But displaying it has been an error.

用logcat更新错误说我的锁已关闭。这意味着我的lock_op从数据库中是1。我能够检索到这个值。但显示它是一个错误。

05-08 16:21:06.040: I/Choreographer(1608): Skipped 177 frames!  The application may be doing too much work on its main thread.
05-08 16:21:15.650: D/dalvikvm(1608): GC_FOR_ALLOC freed 186K, 6% free 3881K/4124K, paused 3ms, total 4ms
05-08 16:21:15.700: W/EGL_emulation(1608): eglSurfaceAttrib not implemented
05-08 16:21:15.730: W/EGL_emulation(1608): eglSurfaceAttrib not implemented
05-08 16:21:15.870: D/am I getting anything(1608): Lock is closed
05-08 16:21:15.870: D/AndroidRuntime(1608): Shutting down VM
05-08 16:21:15.870: W/dalvikvm(1608): threadid=1: thread exiting with uncaught exception (group=0xb2d0eb20)
05-08 16:21:15.870: E/AndroidRuntime(1608): FATAL EXCEPTION: main
05-08 16:21:15.870: E/AndroidRuntime(1608): Process: com.locking, PID: 1608
05-08 16:21:15.870: E/AndroidRuntime(1608): java.lang.NullPointerException
05-08 16:21:15.870: E/AndroidRuntime(1608):     at com.locking.StatActivity$GetStats$1.run(StatActivity.java:160)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at android.app.Activity.runOnUiThread(Activity.java:4713)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at com.locking.StatActivity$GetStats.onPostExecute(StatActivity.java:141)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at com.locking.StatActivity$GetStats.onPostExecute(StatActivity.java:1)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at android.os.AsyncTask.finish(AsyncTask.java:632)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at android.os.Handler.dispatchMessage(Handler.java:102)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at android.os.Looper.loop(Looper.java:136)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at android.app.ActivityThread.main(ActivityThread.java:5017)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at java.lang.reflect.Method.invokeNative(Native Method)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at java.lang.reflect.Method.invoke(Method.java:515)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-08 16:21:15.870: E/AndroidRuntime(1608):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)

1 个解决方案

#1


There are a few things I see here. First, the onPostExecute in your GetStats AsyncTask and the doInBackgrounds on both of your AsyncTasks in your main activity are not overridden. All of those should have the @Override annotation. That way the compiler will then tell you if there's any mismatch between your method and AsyncTask's.

我在这里看到了一些东西。首先,不会覆盖GetStats AsyncTask中的onPostExecute和主活动中两个AsyncTasks上的doInBackgrounds。所有这些都应该有@Override注释。这样编译器就会告诉你方法和AsyncTask之间是否存在不匹配。

Your ProgressDialog is not dismissing because the dialog you are dismissing is not the dialog you created. When you .show() the dialog you need to assign it back to pDialog or else you are not holding the right reference:

您的ProgressDialog没有被解雇,因为您要解雇的对话框不是您创建的对话框。当您.show()对话框需要将其分配回pDialog,否则您没有持有正确的引用:

pDialog = pDialog.show();

Another is that you are not waiting anywhere for your tasks to complete or doing anything when they do. It looks like in your main activity when a user presses your lock_on and lock_off buttons you are executing your tasks and then immediately restarting your main activity. I would create a callback interface and have your activity restart in the callback from onPostExecute. I would also do this for your setTexts to avoid using a runnable.

另一个原因是,您不会在任何地方等待任务完成或做任何事情。当用户按下您执行任务的lock_on和lock_off按钮然后立即重新启动主要活动时,在您的主要活动中看起来就像。我将创建一个回调接口,并在onPostExecute的回调中重新启动活动。我也会为你的setTexts做这个,以避免使用runnable。

Here's some code on how I do that in my app:

以下是我在应用程序中如何执行此操作的一些代码:

This is in my fragment. You could do the same but substitute onCreate for onAttach:

这是我的片段。你也可以这样做,但用onCreate代替onAttach:

static interface TaskCallbacks {
    void onPreExecute();
    void onProgressUpdate(int percent);
    void onCancelled();
    void onPostExecute();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    mCallbacks = (TaskCallbacks) activity;
}

@Override
public void onPostExecute() {
    //Anything you need to do on UI thread
    lockstat.setText(lock);
    DoorStat.setText(door);
    DateStat.setText(date);
}

And then in your AsyncTask:

然后在你的AsyncTask中:

@Override
protected void onPostExecute(Void ignore) {
    if (mCallbacks != null) {
       mCallbacks.onPostExecute();
    //Whatever else you need to do
}

#1


There are a few things I see here. First, the onPostExecute in your GetStats AsyncTask and the doInBackgrounds on both of your AsyncTasks in your main activity are not overridden. All of those should have the @Override annotation. That way the compiler will then tell you if there's any mismatch between your method and AsyncTask's.

我在这里看到了一些东西。首先,不会覆盖GetStats AsyncTask中的onPostExecute和主活动中两个AsyncTasks上的doInBackgrounds。所有这些都应该有@Override注释。这样编译器就会告诉你方法和AsyncTask之间是否存在不匹配。

Your ProgressDialog is not dismissing because the dialog you are dismissing is not the dialog you created. When you .show() the dialog you need to assign it back to pDialog or else you are not holding the right reference:

您的ProgressDialog没有被解雇,因为您要解雇的对话框不是您创建的对话框。当您.show()对话框需要将其分配回pDialog,否则您没有持有正确的引用:

pDialog = pDialog.show();

Another is that you are not waiting anywhere for your tasks to complete or doing anything when they do. It looks like in your main activity when a user presses your lock_on and lock_off buttons you are executing your tasks and then immediately restarting your main activity. I would create a callback interface and have your activity restart in the callback from onPostExecute. I would also do this for your setTexts to avoid using a runnable.

另一个原因是,您不会在任何地方等待任务完成或做任何事情。当用户按下您执行任务的lock_on和lock_off按钮然后立即重新启动主要活动时,在您的主要活动中看起来就像。我将创建一个回调接口,并在onPostExecute的回调中重新启动活动。我也会为你的setTexts做这个,以避免使用runnable。

Here's some code on how I do that in my app:

以下是我在应用程序中如何执行此操作的一些代码:

This is in my fragment. You could do the same but substitute onCreate for onAttach:

这是我的片段。你也可以这样做,但用onCreate代替onAttach:

static interface TaskCallbacks {
    void onPreExecute();
    void onProgressUpdate(int percent);
    void onCancelled();
    void onPostExecute();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    mCallbacks = (TaskCallbacks) activity;
}

@Override
public void onPostExecute() {
    //Anything you need to do on UI thread
    lockstat.setText(lock);
    DoorStat.setText(door);
    DateStat.setText(date);
}

And then in your AsyncTask:

然后在你的AsyncTask中:

@Override
protected void onPostExecute(Void ignore) {
    if (mCallbacks != null) {
       mCallbacks.onPostExecute();
    //Whatever else you need to do
}