草庐IT

android - 通过json在textview中显示数据

coder 2023-12-19 原文

我想通过php显示mysql数据库中的用户详细信息,并在android textview中显示。场景是这样的:当用户登录到他的帐户时,他将被重定向到包含 4 个按钮的仪表板,即:newsfeed、profile、calendar 和 about。当用户单击个人资料按钮时,用户详细信息(如他的姓氏、名字、中间名等)将显示在 TextView 中。当我运行我的应用程序时,它不显示任何内容,但在我的 php 脚本中它返回用户详细信息。这里似乎有什么问题?

这是我的java代码:

package sscr.stag;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.TextView;

public class AdProfile extends Activity {
// All xml labels

TextView txtFname;
TextView txtMname;
TextView txtLname;

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();

// Profile json object
JSONArray user;
JSONObject hay;
// Profile JSON url
private static final String PROFILE_URL     ="http://www.stagconnect.com/StagConnect/admin/TestProfile.php";

// ALL JSON node names
private static final String TAG_PROFILE = "user";
// private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
private static final String TAG_FIRSTNAME = "first_name";
private static final String TAG_MIDDLENAME = "middle_initial";
private static final String TAG_LASTNAME = "last_name";


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adminprofile);


txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.mname);
txtLname = (TextView) findViewById(R.id.lname);

// Loading Profile in Background Thread
new LoadProfile().execute();
}

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


public void test(){

 hay = new JSONObject();

        // Storing each json item in variable
        try {
            String firstname = hay.getString(TAG_FIRSTNAME);
            String middlename = hay.getString(TAG_MIDDLENAME);
            String lastname = hay.getString(TAG_LASTNAME);

            // displaying all data in textview

           txtFname.setText("Firstname: " + firstname);
            txtMname.setText("Middle Name: " + middlename);
            txtLname.setText("Last Name " + lastname);

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

 }

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AdProfile.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
   /**
    * getting Profile JSON
    * */
   protected String doInBackground(String... args) {
    // Building Parameters

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(AdProfile.this);
String post_username = sp.getString("username", "anon");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", post_username));
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "POST",
        params);

// Check your log cat for JSON reponse
Log.d("Profile JSON: ", json.toString());

try {
    // profile json object
    user = json.getJSONArray(TAG_PROFILE);
} catch (JSONException e) {
    e.printStackTrace();
}

return null;
}


protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
test();

}

}
}

这是我的 php 脚本:

<?php


require('admin.config.inc.php');


if (!empty($_POST)) {

    //initial query
    $query = "Select last_name, first_name, middle_initial, designation FROM admin where username = :user";

    $query_params = array(':user' => $_POST['username']);

    //execute query
    try {
        $stmt = $db -> prepare($query);
        $result = $stmt -> execute($query_params);
    } catch (PDOException $ex) {
        $response["success"] = 0;
        $response["message"] = "Database Error!";
        die(json_encode($response));
    }

    // Finally, we can retrieve all of the found rows into an array using fetchAll 
    $rows = $stmt -> fetchAll();

    if ($rows) {
        $response["success"] = 1;
        $response["message"] = "Post Available!";
        $response["user"] = array();

        foreach($rows as $row) {
            $user = array();
            $user["designation"] = $row["designation"];
            $user["middlename"] = $row["middle_initial"];
            $user["firstname"] = $row["first_name"];
            $user["lastname"] = $row["last_name"];

            //update our repsonse JSON data
            array_push($response["user"], $user);
        }

        // echoing JSON response
        echo json_encode($response);

    } else {
        $response["success"] = 0;
        $response["message"] = "No user available!";
        die(json_encode($response));
    }

} else {}


       ?>

 <form action="TestProfile.php" method="POST">
 Username: <input type="text" name="username">
 <input type="submit" value="Submit">
 </form>

这是我的 php 脚本的输出(JSON 响应):

{"success":1,"message":"Post Available!","user":[{"designation":"Student Affairs Office in charge","middlename":"","firstname":"test","lastname":"test"}]}

最佳答案

这是json对象

JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "POST",
    params);

需要在doInbackground中返回json。返回的结果是 onPostExecute

的参数

然后

 test(json);

然后在测试中你可以解析json

编辑:

你还需要改变

 AsyncTask<String, String, String>

AsyncTask<String, String, JSONObject>   

然后

protected JSONObject doInBackground(String... args) {

JSONObject json=null;  
    // Building Parameters

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(AdProfile.this);
String post_username = sp.getString("username", "anon");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", post_username));
// getting JSON string from URL
json = jsonParser.makeHttpRequest(PROFILE_URL, "POST",
        params);

// Check your log cat for JSON reponse
Log.d("Profile JSON: ", json.toString());

try {
    // profile json object
    user = json.getJSONArray(TAG_PROFILE);
} catch (JSONException e) {
    e.printStackTrace();
}

return json;
}

然后在onPostExecute

@Override
protected void onPostExecute(JSONObject result) {
super.onPOstExecute(result);
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
test(result);
}

测试

public void test(JSONObject response){
{
       // parse response here and set text to textview
}

或者

你在doInbackgrond中解析在onPostExecute中更新textview吗

编辑:

代码:

public class AddProfile extends Activity {
    // All xml labels

    TextView txtFname;
    TextView txtMname;
    TextView txtLname;

    // Progress Dialog
    private ProgressDialog pDialog;

    // Profile json object
    JSONArray user;
    JSONObject hay;
    // Profile JSON url
    private static final String PROFILE_URL = "http://www.stagconnect.com/StagConnect/admin/TestProfile.php";

    // ALL JSON node names
    private static final String TAG_PROFILE = "user";
    // private static final String TAG_ID = "id";
    private static final String TAG_USERNAME = "username";
    private static final String TAG_FIRSTNAME = "first_name";
    private static final String TAG_MIDDLENAME = "middle_initial";
    private static final String TAG_LASTNAME = "last_name";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.adminprofile);

        txtFname = (TextView) findViewById(R.id.fname);
        txtMname = (TextView) findViewById(R.id.lname);
        txtLname = (TextView) findViewById(R.id.mname);

        // Loading Profile in Background Thread
        new LoadProfile().execute();
    }

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



        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AddProfile.this);
            pDialog.setMessage("Loading profile ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting Profile JSON
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            String json = null;
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", "admin"));

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(PROFILE_URL);
                httppost.setEntity(new UrlEncodedFormEntity(params));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity resEntity = response.getEntity();
                json = EntityUtils.toString(resEntity);

                Log.i("Profile JSON: ", json.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }

            return json;
        }

        @Override
        protected void onPostExecute(String json) {
            super.onPostExecute(json);
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            try
            {
            hay = new JSONObject(json);
            JSONArray user = hay.getJSONArray("user");
            JSONObject jb= user.getJSONObject(0);
            String firstname = jb.getString("firstname");
            String middlename = jb.getString("middlename");
            String lastname = jb.getString("lastname");

            // displaying all data in textview

            txtFname.setText("Firstname: " + firstname);
            txtMname.setText("Middle Name: " + middlename);
            txtLname.setText("Last Name " + lastname);
            }catch(Exception e)
            {
                e.printStackTrace();
            }

        }

    }
}

json

{ // json object node 
    "success": 1,
    "message": "Post Available!",
    "user": [ // json array user
        {     // json object node 
            "designation": "Student Affairs Office in-charge",
            "middlename": "",
            "firstname": "Jose Patrick",
            "lastname": "Ocampo"
        }
    ]
}

浏览器截图

关于android - 通过json在textview中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21093869/

有关android - 通过json在textview中显示数据的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  4. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  5. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  6. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  7. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  8. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  9. ruby-on-rails - Enumerator.new 如何处理已通过的 block ? - 2

    我在理解Enumerator.new方法的工作原理时遇到了一些困难。假设文档中的示例:fib=Enumerator.newdo|y|a=b=1loopdoy[1,1,2,3,5,8,13,21,34,55]循环中断条件在哪里,它如何知道循环应该迭代多少次(因为它没有任何明确的中断条件并且看起来像无限循环)? 最佳答案 Enumerator使用Fibers在内部。您的示例等效于:require'fiber'fiber=Fiber.newdoa=b=1loopdoFiber.yieldaa,b=b,a+bendend10.times.m

  10. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

随机推荐