如何显示数据库中的值并在android中的textview中显示它。我有一个json解析器的教程,它似乎工作正常。当应用程序运行时,它不会将我的活动加载到textview,也不会显示我的状态。我昨天发布了故障异常,我得到了帮助。该活动似乎永远不会将我的数据加载到textview中。我正在发布我的代码。
这是我的json。我要解析。好像我正在解析它。但没有正确显示。
{"success":1,"message":"Retrieve Status Successful!","status":[{"lock_op":"0","door_op":"0","date_modified":"2015-05-08 09:56:35"}]}
这是状态活动
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;
}
}
这是我的主要活动。
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;
}
}
这是我的清单文件。我确信清单和我的主要活动是正确的。
<?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>
请帮我解决这个问题。
现在是我的新错误。
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)
使用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)
答案 0 :(得分:0)
我在这里看到一些事情。首先,您的onPostExecute
GetStats
中的AsyncTask
和主要活动中doInBackground
的{{1}}都不会被覆盖。所有这些都应该有AsyncTask
注释。这样,编译器会告诉您方法与@Override
之间是否存在不匹配。
您的AsyncTask
没有被解雇,因为您要解雇的对话框不是您创建的对话框。当您ProgressDialog
对话框时,您需要将其分配回.show()
,否则您没有正确的参考:
pDialog
另一个原因是,你不会在任何地方等待你的任务完成或做任何事情。当用户按下您正在执行任务的pDialog = pDialog.show();
和lock_on
按钮,然后立即重新启动主要活动时,您的主要活动就会出现。我将创建一个回调接口,并在lock_off
的回调中重新启动您的活动。我也会为您的onPostExecute
执行此操作,以避免使用setText
。
以下是我在应用中如何做到的一些代码:
这是我的片段。您也可以这样做,但将runnable
替换为onCreate
:
onAttach
然后在你的AsyncTask中:
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);
}