# Plötzlich "java.lang.String cannot be converted to JSONObject"



## Javandroid (27. Jul 2014)

Hallo zusammen,

bin seit gestern am verzweifeln. Ich habe einen Login via JSON/HTTP.
Alles funktionierte auch wunderbar bis gestern. Doch plötzlich taucht die Fehlermeldung:


```
07-27 10:23:19.819: I/Choreographer(17321): Skipped 34 frames!  The application may be doing too much work on its main thread.
07-27 10:23:21.260: D/request!(17321): starting
07-27 10:23:21.681: E/JSON Parser(17321): Error parsing data org.json.JSONException: Value <h1>Login< of type java.lang.String cannot be converted to JSONObject
07-27 10:23:21.681: E/JSON Parser(17321): Error parsing data [Value <h1>Login< of type java.lang.String cannot be converted to JSONObject] 
07-27 10:23:21.681: E/JSON Parser(17321): <h1>Login</h1>
07-27 10:23:21.681: E/JSON Parser(17321):     <form method="post" action="index.php?section=login">
07-27 10:23:21.681: E/JSON Parser(17321):         <table width="350">
07-27 10:23:21.681: E/JSON Parser(17321):             <tr>
07-27 10:23:21.681: E/JSON Parser(17321):                 <td>Benutzername:</td>
07-27 10:23:21.681: E/JSON Parser(17321):                 <td><input type="text" name="name" value="" /></td>
07-27 10:23:21.681: E/JSON Parser(17321):             </tr>
07-27 10:23:21.681: E/JSON Parser(17321):             <tr>
07-27 10:23:21.681: E/JSON Parser(17321):                 <td>Passwort:</td>
07-27 10:23:21.681: E/JSON Parser(17321):                 <td><input type="password" name="pword" /></td>
07-27 10:23:21.681: E/JSON Parser(17321):             </tr>
07-27 10:23:21.681: E/JSON Parser(17321):             <tr>
07-27 10:23:21.681: E/JSON Parser(17321):                 <td></td>
07-27 10:23:21.681: E/JSON Parser(17321):                 <td><input name="submit" type="submit" value="Login" /></td>
07-27 10:23:21.681: E/JSON Parser(17321):             </tr>
07-27 10:23:21.681: E/JSON Parser(17321):         </table>
07-27 10:23:21.681: E/JSON Parser(17321):     </form>
07-27 10:23:21.681: E/JSON Parser(17321):     <center><b><p style="text-decoration:blink; color:#FF0000"></p></b></center>
07-27 10:23:21.681: E/JSON Parser(17321):     <center><b><p style="text-decoration:none; color:#00FF00"></p></b></center>   
07-27 10:23:21.681: E/JSON Parser(17321):     
07-27 10:23:21.681: E/JSON Parser(17321):  
07-27 10:23:21.681: E/JSON Parser(17321):     
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: E/JSON Parser(17321):      
07-27 10:23:21.681: D/JSON String(17321): <h1>Login</h1>
07-27 10:23:21.681: D/JSON String(17321):     <form method="post" action="index.php?section=login">
07-27 10:23:21.681: D/JSON String(17321):         <table width="350">
07-27 10:23:21.681: D/JSON String(17321):             <tr>
07-27 10:23:21.681: D/JSON String(17321):                 <td>Benutzername:</td>
07-27 10:23:21.681: D/JSON String(17321):                 <td><input type="text" name="name" value="" /></td>
07-27 10:23:21.681: D/JSON String(17321):             </tr>
07-27 10:23:21.681: D/JSON String(17321):             <tr>
07-27 10:23:21.681: D/JSON String(17321):                 <td>Passwort:</td>
07-27 10:23:21.681: D/JSON String(17321):                 <td><input type="password" name="pword" /></td>
07-27 10:23:21.681: D/JSON String(17321):             </tr>
07-27 10:23:21.681: D/JSON String(17321):             <tr>
07-27 10:23:21.681: D/JSON String(17321):                 <td></td>
07-27 10:23:21.681: D/JSON String(17321):                 <td><input name="submit" type="submit" value="Login" /></td>
07-27 10:23:21.681: D/JSON String(17321):             </tr>
07-27 10:23:21.681: D/JSON String(17321):         </table>
07-27 10:23:21.681: D/JSON String(17321):     </form>
07-27 10:23:21.681: D/JSON String(17321):     <center><b><p style="text-decoration:blink; color:#FF0000"></p></b></center>
07-27 10:23:21.681: D/JSON String(17321):     <center><b><p style="text-decoration:none; color:#00FF00"></p></b></center>   
07-27 10:23:21.681: D/JSON String(17321):     
07-27 10:23:21.681: D/JSON String(17321):  
07-27 10:23:21.681: D/JSON String(17321):     
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: D/JSON String(17321):      
07-27 10:23:21.681: W/dalvikvm(17321): threadid=12: thread exiting with uncaught exception (group=0x41cc8ba8)
07-27 10:23:21.691: E/AndroidRuntime(17321): FATAL EXCEPTION: AsyncTask #1
07-27 10:23:21.691: E/AndroidRuntime(17321): Process: de.example, PID: 17321
07-27 10:23:21.691: E/AndroidRuntime(17321): java.lang.RuntimeException: An error occured while executing doInBackground()
07-27 10:23:21.691: E/AndroidRuntime(17321): 	at android.os.AsyncTask$3.done(AsyncTask.java:300)
07-27 10:23:21.691: E/AndroidRuntime(17321): 	at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
07-27 10:23:21.691: E/AndroidRuntime(17321): 	at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
07-27 10:23:21.691: E/AndroidRuntime(17321): 	at java.util.concurrent.FutureTask.run(FutureTask.java:242)
07-27 10:23:21.691: E/AndroidRuntime(17321): 	at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-27 10:23:21.691: E/AndroidRuntime(17321): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-27 10:23:21.691: E/AndroidRuntime(17321): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-27 10:23:21.691: E/AndroidRuntime(17321): 	at java.lang.Thread.run(Thread.java:841)
07-27 10:23:21.691: E/AndroidRuntime(17321): Caused by: java.lang.NullPointerException
07-27 10:23:21.691: E/AndroidRuntime(17321): 	at de.example.login.Login$AttemptLogin.doInBackground(Login.java:180)
07-27 10:23:21.691: E/AndroidRuntime(17321): 	at de.example.login.Login$AttemptLogin.doInBackground(Login.java:1)
07-27 10:23:21.691: E/AndroidRuntime(17321): 	at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-27 10:23:21.691: E/AndroidRuntime(17321): 	at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-27 10:23:21.691: E/AndroidRuntime(17321): 	... 4 more
07-27 10:23:22.271: E/WindowManager(17321): android.view.WindowLeaked: Activity de.example.login.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{4283a3d8 V.E..... R......D 0,0-729,192} that was originally added here
07-27 10:23:22.271: E/WindowManager(17321): 	at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
07-27 10:23:22.271: E/WindowManager(17321): 	at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
07-27 10:23:22.271: E/WindowManager(17321): 	at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
07-27 10:23:22.271: E/WindowManager(17321): 	at android.app.Dialog.show(Dialog.java:286)
07-27 10:23:22.271: E/WindowManager(17321): 	at de.example.login.Login$AttemptLogin.onPreExecute(Login.java:157)
07-27 10:23:22.271: E/WindowManager(17321): 	at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
07-27 10:23:22.271: E/WindowManager(17321): 	at android.os.AsyncTask.execute(AsyncTask.java:535)
07-27 10:23:22.271: E/WindowManager(17321): 	at de.example.login.Login.onClick(Login.java:118)
07-27 10:23:22.271: E/WindowManager(17321): 	at android.view.View.performClick(View.java:4438)
07-27 10:23:22.271: E/WindowManager(17321): 	at android.view.View$PerformClick.run(View.java:18422)
07-27 10:23:22.271: E/WindowManager(17321): 	at android.os.Handler.handleCallback(Handler.java:733)
07-27 10:23:22.271: E/WindowManager(17321): 	at android.os.Handler.dispatchMessage(Handler.java:95)
07-27 10:23:22.271: E/WindowManager(17321): 	at android.os.Looper.loop(Looper.java:136)
07-27 10:23:22.271: E/WindowManager(17321): 	at android.app.ActivityThread.main(ActivityThread.java:5001)
07-27 10:23:22.271: E/WindowManager(17321): 	at java.lang.reflect.Method.invokeNative(Native Method)
07-27 10:23:22.271: E/WindowManager(17321): 	at java.lang.reflect.Method.invoke(Method.java:515)
07-27 10:23:22.271: E/WindowManager(17321): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
07-27 10:23:22.271: E/WindowManager(17321): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
07-27 10:23:22.271: E/WindowManager(17321): 	at dalvik.system.NativeStart.main(Native Method)
07-27 10:26:01.942: I/Process(17321): Sending signal. PID: 17321 SIG: 9
```


auf. Und das obwohl der Code unverändert blieb.
Woran könnte das liegen? Ist jemandem soetwas bekannt?

Hier der PHP-CODE:


```
<?php

session_start();

$_SESSION["user"] = @$_POST['name'];
$_SESSION["pword"] = @$_POST['pword'];

    if($_SESSION["user"]&&$_SESSION["pword"])
    {
        include("login_config.php");
    }
    elseif(isset($_POST['submit']))
    {
        $advise1 = "Please enter a username and a password!";
    }

    $Handle = fopen("Ausgabe.txt", 'w');
    fwrite($Handle,  $_REQUEST['referee'] );
    fclose($Handle);
?>

<h1>Login</h1>

    <form method="post" action="index.php?section=login">
        <table width="350">
            <tr>
                <td>Benutzername:</td>
                <td><input type="text" name="name" value="" /></td>
            </tr>
            <tr>
                <td>Passwort:</td>
                <td><input type="password" name="pword" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input name="submit" type="submit" value="Login" /></td>
            </tr>
        </table>
    </form>

    <center><b><p style="text-decoration:blink; color:#FF0000"><?php echo @$advise1;?></p></b></center>
    <center><b><p style="text-decoration:none; color:#00FF00"><?php echo @$advise2;?></p></b></center>

<?php

 ?>
```

Hier der Code zum JSON Parser:


```
package de.example.login;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
 
public class JSONParser {
 
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
 
    // constructor
    public JSONParser() {
 
    }
    
    
    public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.e("Failed",e.getMessage().toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            Log.e("Failed",e.getMessage().toString());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("Failed",e.getMessage().toString());
        }

        try {
            // Create a BufferedReader to parse through the inputStream.
            /*BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);*/
        	//BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
        	BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
        	// Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;
            
            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            
            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
/*
        try {
            jObj = new JSONObject(json.substring(3));
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
        }
*/        
       // Try to parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
            Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
            Log.d("JSON String",json);
        }

        // Return the JSON Object.
        return jObj;
    }
    
 
    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {
 
        // Making HTTP request
        try {
 
            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
 
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
 
            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
     //           String paramString = URLEncodedUtils.format(params, "HTTP.UTF-8");
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);
 
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.e("Failed",e.getMessage().toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            Log.e("Failed",e.getMessage().toString());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("Failed",e.getMessage().toString());
        }
 
        try {
 //           BufferedReader reader = new BufferedReader(new InputStreamReader(
 //                   is, "iso-8859-1"), 8);
 //       	BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
        	BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
        	StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
 
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
            Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
            Log.d("JSON String",json);
        }
 
/*        
        try {
            jObj = new JSONObject(json.substring(3));
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
        }
 */       
        // return JSON String
        return jObj;
    }
}
```
Die Auskommentierten Stelen sind die verzweifelten Versuche es wieder zum laufen zu bekommen.

Hoffe mit kann jemand helfen oder hat ein paar Tipps.


----------



## JavaMeister (27. Jul 2014)

Du versuchst HTML nach JSON zu parsen. Das funktioniert nicht.


----------



## Javandroid (27. Jul 2014)

Vielen Dank. Das Ich das nicht kann weiß Ich auch. Aber wie kann das sein, wo ist der Fehler? Es gibt nun über 9 Wochen und seit gestern plötzlich nicht mehr.


----------



## JavaMeister (27. Jul 2014)

Du rufst eine Seite auf, die ein Loginformular ausgibt. Wie soll das jemals funktioniert haben?

Es wurde noch mehr geändert, als das was du hier schreibst.


----------



## Javandroid (27. Jul 2014)

Durch das inkludieren der login_config Datei handelt es sich ja nicht mehr nur um die Anzeige eines Loginformulars. Es hat 9 Wochen lang funktioniert und plötzlich nicht mehr. Die Änderungen habe Ich nachträglich eingefügt um das Programm verzweifelt wieder zum laufen zu bekommen, leider erfolglos .


----------



## JavaMeister (27. Jul 2014)

Welchen String willst du nach Json parsen?

Weißt du was json ist?


----------



## Javandroid (27. Jul 2014)

Das eingegebene Passwort und den Username möchte Ich nach JSON parsen.
Ja das weiß ich und kenne auch das eingentliche Format.
Mir ist jedoch unklar wo hier der Fehler sein soll, es ging ja 9 Wochen lang und warum das Programm versucht den HTML-Code "mitzuparst", obwohl das gar nicht passieren dürfte.


----------



## JavaMeister (27. Jul 2014)

Dann kann man leider nicht ehelfen.

Das Programm macht was es soll.


----------



## Javandroid (27. Jul 2014)

Was müsste denn Ihrer Meinung nach geändert werden, damit nur der Username und das Passwort zu JSON geparst werden`?


----------



## JavaMeister (27. Jul 2014)

Username und Passwort als JSON String von php geliefert werden.


----------

