Autore Topic: Android PhP MySQL JSONParser  (Letto 375 volte)

Offline ZioArnold

  • Nuovo arrivato
  • *
  • Post: 8
  • Respect: 0
    • Mostra profilo
  • Dispositivo Android:
    Samsug Galaxy S2 - GT 9100
  • Sistema operativo:
    Windows 10 Pro
Android PhP MySQL JSONParser
« il: 07 Novembre 2015, 21:46:29 CET »
0
Salve programmatori...
Qualcuno sa risolvere questo problema? Ho guardato quasi dappertutto, non so come si potrebbe fixare...

Codice (Java): [Seleziona]
package com.example.arnold.itsosgadda;

import android.app.ActionBar;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;

import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("deprecation")
public class CommunicationsActivity extends Activity {
    private String jsonResult;
    //private String url = "https://drive.google.com/open?id=0By57NyAMoNAhWDl2ckJvMy1qLUU";
    private String url = "http://xxx.xxx.xxx.xxx:xxxx/config.php";
    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.communications_news_layout);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        connect();

        ActionBar actionBar = getActionBar();
        assert actionBar != null;
        actionBar.setIcon(R.mipmap.ic_launcher);
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffeb3b")));
    }

    private void connect() {
        String data;
        List<String> listData = new ArrayList<>();
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(),
                android.R.layout.simple_list_item_1, listData);
        listView = (ListView) findViewById(R.id.listView);
        try {DefaultHttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(String.valueOf(url));
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-Type", "application/json");
            HttpResponse response = client.execute(request);
            response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            data = EntityUtils.toString(entity);
            Log.e("log_data", data);
            try {
                JSONParser jsonParser = new JSONParser();
                JSONArray jsonArray = (JSONArray) jsonParser.parse(data);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject obj = jsonArray.getJSONObject(i);
                    String name = obj.optString("push_name");
                    String link = obj.getString("link");
                    Log.e("log_data", name);

                    listData.add(name);
                    listData.add(link);
                    listView.setAdapter(adapter);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /*final CommunicationsActivity activity = this;
    final String url = "http://www.itsosgadda.it/index.php/comunicazioni-pubbliche";
    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
        ActionBar actionBar = getActionBar();
        assert actionBar != null;
        actionBar.setIcon(R.mipmap.ic_launcher);
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffeb3b")));
        //Shows me status bar progress

        setContentView(R.layout.communications_news_layout);
        WebView webView = (WebView) findViewById(R.id.webView);
        //Enables JS
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setBuiltInZoomControls(true);
        //noinspection deprecation
        webView.getSettings().setDefaultZoom(FAR);
        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                activity.setTitle(R.string.loading_progress);
                activity.setProgress(progress * 100);
                if (progress == 100) {
                    activity.setTitle(R.string.app_name);
                }
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                // Handle the error
                Log.i("WEB_VIEW_COMMUNICATIONS", "Error code: " + errorCode);
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        webView.loadUrl(url);
    }*/


}
Codice: [Seleziona]
<?php
/**
 * Created by PhpStorm.
 * User: Arnol'd
 * Date: 07.11.2015
 * Time: 15:27
 */
$username = 'app';
$password = '4826159g';
$hostname = 'xxx.xxx.xxx.xxx:xxxx';
$database = 'app_db';

$conn = new mysqli($hostname, $username, $password, $database);
if ($conn->connect_error) {
    die("Connection failed:" . $conn->connect_error);
}
$sql = "select * from push";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo $data = $row['push_name'] . '  <a href="'.$row['link'].'">' . 'Download' . "<br>";

    }
}
else{
    echo "0 results";
}
$conn->close();
Codice: [Seleziona]
11-07 21:40:48.709 10358-10358/com.example.arnold.itsosgadda E/log_data: Comunicazione n.129  <a href="http://www.itsosgadda.it/comunicazioni/pubbliche/2015-16%20Comunicazione%20129%20Uscita%20didattica%203B%20museo%20del%20computer%20Fornovo.pdf">Download<br>
11-07 21:40:48.729 10358-10358/com.example.arnold.itsosgadda W/System.err: Unexpected character (C) at position 0.
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at com.example.arnold.itsosgadda.CommunicationsActivity.connect(CommunicationsActivity.java:71)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at com.example.arnold.itsosgadda.CommunicationsActivity.onCreate(CommunicationsActivity.java:40)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at android.app.Activity.performCreate(Activity.java:5231)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2285)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at android.app.ActivityThread.access$800(ActivityThread.java:138)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1236)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at android.os.Looper.loop(Looper.java:149)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5061)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:603)
11-07 21:40:48.739 10358-10358/com.example.arnold.itsosgadda W/System.err:     at dalvik.system.NativeStart.main(Native Method)

Offline pietroconti89

  • Utente normale
  • ***
  • Post: 164
  • Respect: +19
    • Mostra profilo
  • Dispositivo Android:
    Galaxy Note 3 N9005
  • Sistema operativo:
    Windows / Mac OSX
Re:Android PhP MySQL JSONParser
« Risposta #1 il: 08 Novembre 2015, 02:36:24 CET »
0
Ciao ci sono una serie di problemi a monte ... se esegui una richiesta http devo utilizzare una asyntask o meglio ancora affidarti a librerie come async http o okhttp ... ma tralasciando questo ... fatta la select dalla parte php devi fare così ....
Codice: [Seleziona]
$r=mysql_query($sql,$con);

        while($row=mysql_fetch_array($r))
        {
                $flag[]=$row;
        }
         
        print(json_encode($flag));
        mysql_close($con);


Al posto di

Codice: [Seleziona]
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo $data = $row['push_name'] . '  <a href="'.$row['link'].'">' . 'Download' . "<br>";

    }
}
else{
    echo "0 results";
}
$conn->close();


Saluti

Offline ZioArnold

  • Nuovo arrivato
  • *
  • Post: 8
  • Respect: 0
    • Mostra profilo
  • Dispositivo Android:
    Samsug Galaxy S2 - GT 9100
  • Sistema operativo:
    Windows 10 Pro
Re:Android PhP MySQL JSONParser
« Risposta #2 il: 08 Novembre 2015, 11:17:56 CET »
0
Ciao grazie della risposta, ma se io vorrei visualizzare il nome della comunicazione e il suo link associato in formato (hypertext)
tipo <a href......>
COme faccio in questo caso? Perchè il link lo devo visualizzre con Linkify.ALL per la seguente scarica della comunicazione in formato pdf, o visualizzazione con pdf reader integrato di Google.


Codice (Java): [Seleziona]
OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            data = response.body().string();

Il nuovo codice sarà così? E sara comprensibile al JSONParser?

Post unito: [time]08 Novembre 2015, 11:48:06 CET[/time]
Codice: [Seleziona]
-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime: FATAL EXCEPTION: main
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime: Process: com.example.arnold.itsosgadda, PID: 32408
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime: java.lang.NoClassDefFoundError: okio.Okio
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.squareup.okhttp.internal.http.HttpConnection.<init>(HttpConnection.java:90)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.squareup.okhttp.Connection.connectSocket(Connection.java:208)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.squareup.okhttp.Connection.connect(Connection.java:172)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.squareup.okhttp.Connection.connectAndSetOwner(Connection.java:367)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.squareup.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:328)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:245)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.squareup.okhttp.Call.getResponse(Call.java:267)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:224)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:195)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.squareup.okhttp.Call.execute(Call.java:79)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.example.arnold.itsosgadda.CommunicationsActivity.connect(CommunicationsActivity.java:54)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.example.arnold.itsosgadda.CommunicationsActivity.onCreate(CommunicationsActivity.java:37)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:5231)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2285)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:138)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1236)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:149)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5061)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:603)
11-08 11:47:19.620 32408-32408/com.example.arnold.itsosgadda E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
11-08 11:47:30.190 32408-32408/com.example.arnold.itsosgadda I/Process: Sending signal. PID: 32408 SIG: 9

Post unito: [time]08 Novembre 2015, 13:12:49 CET[/time]
https://www.youtube.com/watch?v=YfAqv0pIBBA
Guardando questo video, ho adattato al mio progetto, sembri che i problemi primari sono andati, ma compaie sempre un NPE...
Qualcuno mi sa dire?
JSON PhP ANDROID NPE - Stack Overflow
« Ultima modifica: 08 Novembre 2015, 13:13:15 CET da ZioArnold »