dqcqcqwq38860 2013-03-09 00:47
浏览 129
已采纳

字符串无法转换为JSON数组[关闭]

I am getting the following error every time I try to execute my code:

03-09 00:41:23.022: E/JustDealsUtils(1163): Error parsing to json on getJarrayFromString(); org.json.JSONException: Value Database of type java.lang.String cannot be converted to JSONArray
03-09 00:41:23.022: E/ActivityTab(1163): Error at fillPromotionList(): java.lang.NullPointerException

Java snipped for fillPromotionList():

public void onTaskCompleted(String result) {
  try {
    // converting the response into json array
    if(result != "") {
      jarray = utils.getJarrayFromString(result);

      // total number of rows for a query
      int mysqlSize = (jarray.getJSONObject(0)
        .getInt("numRows"));

      Log.i(DEBUG, "From " + from + " to " + mysqlSize);

      if(from <= mysqlSize) {
        int rows;
        if(jarray.length() > 0) {
          Log.i(DEBUG, "From " + from + " to " + Math.floor(mysqlSize / nr) * nr);
          if(from + 5 <= Math.floor(mysqlSize / nr) * nr) {
            rows = jarray.length();
          } else {
            rows = mysqlSize % nr + 1;
            Utils.IS_ENDED_PROMO_LIST = true;
          }
          ArrayList < String > list = new ArrayList < String > ();
          for(int i = 1; i < rows; i++) {
            JSONObject row = jarray.getJSONObject(i);
            soid.add(row.getInt("bid"));
            soTitle.add(row.getString("bTitle"));
            soCode.add(row.getString("bCode"));
            soPrice.add(row.getString("bPrice") + "£");
            soDescription.add(row.getString("bDescription"));
            soModule.add(row.getString("bModule"));
            soImage.add(Utils.PATH + row.getString("bImage"));
            soDiscount.add(row.getInt("bSpecialDiscount"));
            list.add(row.getString("bImage"));
            if(!db.hasIDBooks(row.getInt("bid"))) db.createRowOnBooks(row.getInt("bid"), row.getString("bTitle"), row.getString("bCode"), row.getString("bPrice"), row.getString("bDescription"), row.getString("bModule"), Utils.PATH + row.getString("bImage"), row.getString("bSpecialOffer"), row.getInt("bSpecialDiscount"), row.getString("bDateAdded"));
          }
          new DownloadImages(list, soAdapter)
            .execute();
        }
      }
      postParameters.removeAll(postParameters);
    } else {
      Utils.IS_ENDED_PROMO_LIST = true;
      if(rlLoading.isShown()) {
        rlLoading.startAnimation(fadeOut());
        rlLoading.setVisibility(View.INVISIBLE);
      }
    }
  } catch(Exception e) {
    Log.e(DEBUG, "Error at fillPromotionList(): " + e.toString());
  }
}
});

I have the same code written for another list function and it works fine. I am unable to rectify the problem.

Moreover, it is also pointing towards a null pointer exception??

Here is my PHP API for this Code:

<?php
    include("MysqlConnection.php");
    $from = $_POST["from"];
    $nr = $_POST["nr"];
    // those variables are for search
    $title = $_POST["title"];
    $code = $_POST["code"];
    $price = $_POST["price"];
    $module = $_POST["module"];
    $order = $_POST["order"];
    $by = $_POST["by"];


    $sql = "SET CHARACTER SET utf8";
    $db->query($sql);

    if(isset($from) && isset($nr)){
        // we need to know how many rows are in total for this query
        $sql = "SELECT * FROM `books` WHERE `bSpecialOffer='true' AND `bCode` LIKE '%$code%' AND `bTitle` LIKE '%$title%' AND `bModule` LIKE '%$module%'";
        $query = $db->query($sql);

        $rows = array();
        $rows[] = array("numRows"=>$db->numRows($query));

        // if those 2 var are set then we order the query after them
        if(isset($order) && isset($by)){
            $sql .= " ORDER BY `$order` $by LIMIT $from, $nr";
        }else{
            $sql .= "LIMIT $from, $nr";
        }

        $query = $db->query($sql);

        if($db->numRows($query)!=0){
            while($row = mysql_fetch_assoc($query)) {
                $rows[] =  $row;
            }
            print_r(json_encode($rows));
        }
    }

    $db->closeConnection();
?>

Actually error also mentions DATABASE VALUE. Does that mean error lies in the PHP API?

Finally, here is my JSON array part in utils.java:

 public JSONArray getJarrayFromString(String result) {
   // Parsing string to JSON Array
   try {
     jarray = new JSONArray(result);
   } catch(JSONException e) {
     Log.e(DEBUG, "Error parsing to json on getJarrayFromString(); " + e.toString());
   }

   return jarray;
 }

Your suggestions and opinions would be highly appreciated. Many thanks.

Snippet from SQL database for BOOKS table.

CREATE TABLE `books` (
  `bid` int(11) NOT NULL auto_increment,
  `bCode` varchar(50) NOT NULL,
  `bTitle` varchar(100) NOT NULL,
  `bPrice` int(50) NOT NULL,
  `bDescription` longtext NOT NULL,
  `bModule` varchar(50) NOT NULL,
  `bImage` varchar(80) NOT NULL,
  `bDateAdded` date NOT NULL,
  `bSpecialOffer` varchar(5) NOT NULL,
  `bSpecialDiscount` int(3) NOT NULL,
  PRIMARY KEY  (`bid`),
  UNIQUE KEY `bTitle` (`bTitle`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=49 ;

--
-- Dumping data for table `books`
--

INSERT INTO `books` VALUES(1, "MDAI001", "Apocalyptic AI", 50, "Author: Robert M.Geraci

Edition: 5th Edition 

Topics: Intelligence Agents,Solving problems by seraching, Beyond classical search, Algorithms and Adversarial search, logical agents", "MDAI72", "image26.jpg", "2013-01-12", "true", 30);
INSERT INTO `books` VALUES(19, 'MDAI002', 'Programming Game AI by Example', 15, 'Author: Mat Buckland

Edition: 2nd Edition 

Topics: Learning from examples, Knowledge in learning, Reinforcement learning, Learning probabalistic model, Non parametric models', 'MDAI72', 'image27.jpg', '2013-01-25', 'false', 0);
INSERT INTO `books` VALUES(20, 'MDAI003 ', 'Artificial Inteligence', 26, 'Author: George F Luger

Edition: 1st Edition 

Topics: Artificial neural networks, Language models, Speech recognition, Syntactic analysis, Image formation, Reconstructing the 3D world, Machine translation ', 'MDAI72', 'image28.jpg', '2012-05-18', 'false', 0);
INSERT INTO `books` VALUES(21, 'MDAI004 ', 'Artificial Intelligence Programming', 10, 'Author: Peter Narvig

Edition: 3rd Edition 

Topics: Learning from examples, Knowledge in learning, Reinforcement learning, Learning probabalistic model, Non parametric models
', 'MDAI72', 'image29.jpg', '2012-03-17', 'false', 0);
INSERT INTO `books` VALUES(22, 'MDAI005', 'Artificial Intelligence: A Systems Approach', 35, 'Author: Dan Jones

Edition: 2nd Edition 

Topics: Robotic perception, Robotic software architectures, Strong AI vs Weak AI,  The ethics and risks of developing AI, Can machines really think? 
', 'MDAI72', 'image30.jpg', '2012-01-20', 'false', 0);
INSERT INTO `books` VALUES(24, 'MDSC001 ', 'Distributed and Cloud Computing', 30, 'Author: Kay Hwang

Edition: 3rd Edition 

Topics: Modern distributed models, Peer-to-peer computing, Open source and commercial vendors', 'MDSC48', 'image21.jpg', '2012-02-16', 'false', 0);
INSERT INTO `books` VALUES(25, 'MDSC002', 'Computing in the Social Sciences and Humanities', 12, 'Author: Orville Vernon Burton 

Edition: 5nd Edition 

Topics:A lively, hands-on introduction for teachers and scholars in the humanities and social sciences, this book-and-CD package will inspire even the faint-hearted to take the technological bull by the horns and make efficient, informed use of computer and Internet resources. New technology is changing the very nature of research and teaching in the social sciences and humanities.', 'MDSC48', 'image22.jpg', '2012-03-17', 'false', 0);
INSERT INTO `books` VALUES(26, 'MDSC003', 'Identity in the age of Cloud Computing ', 30, 'Author: J.D.Lasica

Edition: 1st Edition 

Topics: The Mobile Generation: Global Transformations at the Cellular Level, Civic Engagement on the Move: How Mobile Media Can Serve the Public Good, Identity in the Age of Cloud Computing: The next-generation Internet’s impact on business, governance and social interaction', 'MDSC48', 'image23.jpg', '2012-10-10', 'false', 0);
INSERT INTO `books` VALUES(27, 'MDSC004', 'To the Cloud- Powering an Enterprise', 23, 'Author: Pankaj Arora

Edition: 4th Edition 

Topics: Understand the Cloud
Understand the Value Proposition
Chart the Cloud Landscape', 'MDSC48', 'image24.jpg', '2012-01-12', 'true', 20);
INSERT INTO `books` VALUES(28, 'MDSC005 ', 'Building Virtual Communities', 35, 'Author: K. Ann Renninger

Edition: 1st Edition 

Topics: Building Virtual Communities examines how learning and cognitive change are fostered by online communities. Contributors to this volume explore this question by drawing on their different theoretical backgrounds, methodologies, and personal experience with virtual communities. Each chapter discusses the different meanings of the terms community, learning, and change', 'MDSC48', 'image25.jpg', '2012-09-23', 'false', 0);
INSERT INTO `books` VALUES(29, 'MDSE001', 'Software Engineering: Principles and Practice', 12, 'Author: Hans Van Vliet 

Edition: 3rd Edition 

Topics: 
Introduction to Software Engineering Management, The Software Life Cycle Revisited, Configuration Management, People Management and Team Organization, On Managing Software Quality, Cost Estimation, Project Planning and Control 
', 'MDSE80', 'image16.jpg', '2012-05-17', 'false', 0);
INSERT INTO `books` VALUES(30, 'MDSE002', 'Software Engineering: A Practioners Approach', 25, 'Author: Roger.S.Pressman

Edition: 7th Edition 

Topics: 
The seventh edition is considerably more than a simple update. The book has been revised and restructured to improve pedagogical flow and emphasize new and important software engineering processes and practices. In addition, a revised and updated “support system,” illustrated below, provides a comprehensive set of student, instructor, and professional resources to complement the content of the book.
', 'MDSE80', 'image17.jpg', '2012-07-19', 'false', 0);
INSERT INTO `books` VALUES(31, 'MDSE003', 'Software Engineering for Students: A programming approach', 25, 'Author: Douglas Bell

Edition: 4th Edition 

Topics: Software Engineering for Students presents a range of current techniques and tools for people who have experienced the pleasures of writing programs and who want to see how things change in the scale up to large programs and software systems.

', 'MDSE80', 'image18.jpg', '2012-04-13', 'false', 0);
INSERT INTO `books` VALUES(32, 'MDSE004', 'Object Oriented Software', 32, 'Author: Michael Smith 

Edition: 2nd Edition 

Topics: The book covers ANSI C++ and is illustrated with numerous programming examples. The first few chapters introduce computer programming for those who have no previous programming knowledge. The book avoids the early use of low level constructs such as pointers so that the key object-oriented concepts can be fully introduced', 'MDSE80', 'image19.jpg', '2012-04-17', 'false', 0);
INSERT INTO `books` VALUES(33, 'MDPG001', 'iPhone Programming', 14, 'Author: Alasdair Allan

Edition: 1st Edition 

Topics: The book guides you through developing your first application for the iPhone, from opening Xcode for the first time, to submitting your application to the App Store. You''ll learn about Objective-C and the core frameworks needed to develop for the iPhone by writing applications that use them, giving you a basic framework for building your own applications independently.
', 'MDPG70', 'image6.jpg', '2012-07-19', 'false', 0);
INSERT INTO `books` VALUES(34, 'MDPG002', 'Java: Introduction to Problem Solving and Programming', 29, 'Author: Walter Savitch

Edition: 1st Edition 

Topics: For introductory Computer Science courses using Java (CS1with Java), and other introductory programming courses in departments of Computer Science, Computer Engineering, Computer Information Systems, Management Information Systems, Information Technology, and Business.', 'MDPG70', 'image7.jpg', '2012-07-12', 'false', 0);
INSERT INTO `books` VALUES(35, 'MDSE005', 'Object-Oriented and Classical Software Engineering', 26, 'Author: Stephen R.Schach

Edition: 8th Edition 

Topics: Building on seven strong editions, the eighth edition maintains the organization and approach for which "Object-Oriented and Classical Software Engineering" is known while making significant improvements and additions to content as well as problems and projects.
', 'MDSE80', 'image20.jpg', '2012-10-17', 'false', 0);
INSERT INTO `books` VALUES(36, 'MDPG003', 'Web Services with Perl', 18, 'Author: Randy J. Ray

Edition: 2nd Edition 

Topics: Given Perl''s natural fit for web applications development, it''s no surprise that Perl is also a natural choice for web services development. It''s the most popular web programming language, with strong implementations of both SOAP and XML-RPC, the leading ways to distribute applications using web services. But books on web services focus on writing these applications in Java or Visual Basic, leaving Perl programmers with few resources to get them started. Programming Web Services with Perl changes that, bringing Perl users all the information they need to create web services using their favorite language.', 'MDPG70', 'image8.jpg', '2012-07-20', 'false', 0);
INSERT INTO `books` VALUES(37, 'MDPG004', 'Effective TCP/IP Programming: 44 Tips to Improve Your Network Programs', 34, 'Author: Jon C. Snader

Edition: 4th Edition 

Topics: An excellent next-step for students who have read Stevens'' TCP/IP Illustrated series, this book is designed to boost programmers to a higher level of competence by focusing on the protocol suite''s more subtle features and techniques. In forty-four concise, self-contained lessons, this book offers experience-based tips, practices, and rules of thumb for learning high-performance TCP/IP programming techniques. Moreover, it shows you how to avoid many of TCP/IP''s most common trouble spots.', 'MDPG70', 'image9.jpg', '2012-02-25', 'false', 0);
INSERT INTO `books` VALUES(38, 'MDPG005', 'Pro Java Programming', 34, 'Author: Brett Spell

Edition: 2nd Edition 

Topics: Pro Java Programming, Second Edition covers the J2SE 5.0 platform and the core Java development kit. It takes advantage of the finer points of the core and standard edition of Java 2. You''ll discover the particulars of working with the Java language and APIs to develop applications in many different contexts.', 'MDPG70', 'image10.jpg', '2012-10-20', 'false', 0);
INSERT INTO `books` VALUES(39, 'MDEC001', 'E-commerce: Business. Technology. Society', 26, 'Author: Kenneth C. Laudon

Edition: 2nd Edition 

Topics: Electronic commerce: Business. Technology. Society. provides an overview of the current and next generations of e-commerce. The book emphasizes the three major driving forces behind e-commerce: business development, technology change, and social controversies.', 'MDEC20', 'image11.jpg', '2012-08-18', 'false', 0);
INSERT INTO `books` VALUES(40, 'MDEC002 ', 'E-commerce Technology Foundations', 17, 'Author: Davis and Benamati

Edition: 3rd Edition 

Topics: In E-Commerce Basics, the authors introduce the basic technological infastructure and business issues to understand when analyzing the feasibility of e-commerce initiatives
', 'MDEC20', 'image12.jpg', '2012-10-16', 'false', 0);
INSERT INTO `books` VALUES(41, 'MDEC003', 'E-business and E-commerce Management', 21, 'Author: Dave Chaffey

Edition: 3rd Edition 

Topics:A comprehensive assessment of the management issues faced in implementing e-business solutions, this book is suitable for students or practitioners of e-business, e-commerce or e-marketing at any level. Each chapter contains management issues, activities and answers, case studies, questions for debate, self-assessment exercises, discussion, essay and exam questions, further reading, web links and more.
', 'MDEC20', 'image13.jpg', '2012-05-13', 'false', 0);
INSERT INTO `books` VALUES(42, 'MDEC004', 'The Complete E-Commerce Book', 22, 'Author: Janice Reynolds 

Edition: 2nd Edition 

Topics: The Complete E-Commerce Book offers a wealth of information on how to design, build and maintain a successful web-based business.... Many of the chapters are filled with advice and information on how to incorporate current e-business principles
', 'MDEC20', 'image14.jpg', '2012-08-27', 'false', 0);
INSERT INTO `books` VALUES(43, 'MDEC005', 'Design and Launch an E-Commerce Business in a Week (ClickStart Series)', 35, 'Author: Jason Rich

Edition: 3rd Edition 

Topics: In just days, you can build your own eCommerce website, reach potential customers by the millions, process orders 24/7 and accept payments from all over the world—with no technical background or graphic design skills!
', 'MDEC20', 'image15.jpg', '2012-08-20', 'false', 0);
INSERT INTO `books` VALUES(44, 'MDCS001', 'Corporate Computer Security', 30, 'Author: Randall J. Boyle

Edition: 3rd Edition 

Topics: A strong business focus through a solid technical presentation of security tools. Boyle/Panko provides a strong business focus along with a solid technical understanding of security tools. This text gives readers the IT security skills they need for the workplace. This edition is more business focused and contains additional hands-on projects, coverage of wireless and data security, and case studies.', 'MDCS10', 'image1.jpg', '2012-08-10', 'false', 0);
INSERT INTO `books` VALUES(45, 'MDCS002', 'Computer Security: Art and Science', 29, 'Author: Matt Bishop

Edition: 5th Edition 

Topics: This book provides a thorough and comprehensive introduction to computer security. It covers both the theoretical foundations and practical aspects of secure systems.', 'MDCS10', 'image2.jpg', '2012-08-01', 'false', 0);
INSERT INTO `books` VALUES(46, 'MDCS003', 'Introduction to Computer Security ', 10, 'Author: Ralph Argiento

Edition: 3rd Edition 

Topics: Introduction to Computer Security is a teaching and learning tool that was designed for use in a classroom setting, encouraging students to learn by using these new technologies hands-on.
', 'MDCS10', 'image3.jpg', '2012-10-22', 'false', 0);
INSERT INTO `books` VALUES(47, 'MDCS004', 'A basic Introduction to Computer Security ', 17, 'Author: Addison Wesley 

Edition: 3rd Edition 

Topics:  Introduction to Computer Security, 1e does NOT focus on the mathematical and computational foundations of security, and it does not assume an extensive background in computer science. Instead it looks at the systems, technology, management, and policy side of security, and offers students fundamental security concepts and a working knowledge of threats and countermeasures with “just-enough” background in computer science. The result is a presentation of the material that is accessible to students of all levels.', 'MDCS10', 'image4.jpg', '2012-07-22', 'false', 0);
INSERT INTO `books` VALUES(48, 'MDCS005 ', 'Principles of Computer Security CompTIA Security + and Beyond', 21, 'Author: Gregory White

Edition: 2nd Edition 

Topics: This up-to-date, full-color guide discusses communication, infrastructure, operational security, attack prevention, disaster recovery, computer forensics, and much more.
', 'MDCS10', 'image5.jpg', '2012-10-22', 'false', 0);
  • 写回答

1条回答 默认 最新

  • dshmvqnl98119 2013-03-09 01:04
    关注

    In PHP, print_r is for debugging, and prints human-readable information about a variable. You want to use print

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)