2017-10-06 64 views
0

我试着去解析是在网上服务器和存储存在这样String data = "";一个空字符串,但是当我尝试分析它,我看到日志JSON字符串我看到从服务器的响应显示所有的JSON代码(括号和引号和jsonobject),当我只需要它解析一个特定的字符串存储在空字符串。这里是JSON:解析从URL JSON字符串,并将其存储在空字符串

{ 
"main1": {"bnl":"code"} 
} 

的httphanlder

import android.util.Log; 

import java.io.BufferedInputStream; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.ProtocolException; 
import java.net.URL; 


public class HttpHandler { 
private static final String TAG = HttpHandler.class.getSimpleName(); 

public HttpHandler() { 
} 

public String makeServiceCall(String reqUrl) { 
    String response = null; 
    try { 
     URL url = new URL(reqUrl); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setRequestMethod("GET"); 
     // read the response 
     InputStream in = new BufferedInputStream(conn.getInputStream()); 
     response = convertStreamToString(in); 
    } catch (MalformedURLException e) { 
     Log.e(TAG, "MalformedURLException: " + e.getMessage()); 
    } catch (ProtocolException e) { 
     Log.e(TAG, "ProtocolException: " + e.getMessage()); 
    } catch (IOException e) { 
     Log.e(TAG, "IOException: " + e.getMessage()); 
    } catch (Exception e) { 
     Log.e(TAG, "Exception: " + e.getMessage()); 
    } 
    return response; 
} 

private String convertStreamToString(InputStream is) { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line).append('\n'); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 
} 

,这是在MainActivity

public class MainActivity extends ActionBarActivity { 

DataBaseHandler db; 
private AlertDialog dialog; 
public static final int IntialQteOfDayId = 8; 
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ; 
final Context context = this; 
SharedPreferences preferences; 
private static final int RESULT_SETTINGS = 1; 
private NativeExpressAdView mNativeExpressAdView; 
// URL of object to be parsed 
// This string will hold the results 

private String TAG = MainActivity.class.getSimpleName(); 
String data = ""; 
private ProgressDialog pDialog; 
// URL to get contacts JSON 
private static String url = "https://yourdomain.com/test.json"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
     getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 
     getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark)); 
    } 
    new GetAd().execute(); 
    LinearLayout layout = (LinearLayout)findViewById(R.id.layoutId); 
    // Create a native express ad. The ad size and ad unit ID must be set before calling 
    // loadAd. 
    mNativeExpressAdView = new NativeExpressAdView(MainActivity.this); 
    mNativeExpressAdView.setAdSize(new AdSize(AdSize.FULL_WIDTH, 90)); 
    mNativeExpressAdView.setAdUnitId(data); 
    // Create an ad request. 
    AdRequest.Builder adRequestBuilder = new AdRequest.Builder(); 
    // Start loading the ad. 
    mNativeExpressAdView.loadAd(adRequestBuilder.build()); 
    // Add the NativeExpressAdView to the view hierarchy. 
    layout.addView(mNativeExpressAdView); 
    Typeface bold = Typeface.createFromAsset(getAssets(), 
      "fonts/extrabold.otf"); 
    db = new DataBaseHandler(this); 
    db.openDataBase() ; 
    TextView cat = (TextView) findViewById(R.id.titlecat); 
    cat.setTypeface(bold); 
    TextView alls = (TextView) findViewById(R.id.titlest); 
    alls.setTypeface(bold); 
    TextView fav = (TextView) findViewById(R.id.titlefav); 
    fav.setTypeface(bold); 
    TextView qday = (TextView) findViewById(R.id.titleqday); 
    qday.setTypeface(bold); 
    TextView rate = (TextView) findViewById(R.id.titleqrate); 
    rate.setTypeface(bold); 
    btn_quotes = (ImageView) findViewById(R.id.btn_quotes); 
    //btn_authors= (Button) findViewById(R.id.btn_authors); 
    btn_categories = (ImageView) findViewById(R.id.btn_categories); 
    btn_favorites = (ImageView) findViewById(R.id.btn_favorites); 
    btn_qteday = (ImageView) findViewById(R.id.btn_qteday); 
    btn_rateus = (ImageView) findViewById(R.id.btn_rateus); 

    btn_quotes.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(MainActivity.this, 
        QuotesActivity.class); 
      intent.putExtra("mode", "alltext"); 
      startActivity(intent); 
     } 
    }); 

    /*btn_authors.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      Intent author = new Intent(MainActivity.this, 
        AuteursActivity.class); 
      startActivity(author); 
     } 
    });*/ 

    btn_favorites.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      Intent favorites = new Intent(MainActivity.this, 
        QuotesActivity.class); 
      favorites.putExtra("mode", "isFav"); 
      startActivity(favorites); 
     } 
    }); 

    btn_categories.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      Intent category = new Intent(MainActivity.this, 
        CategoryActivity.class); 
      startActivity(category); 
     } 
    }); 

    btn_qteday.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      preferences = PreferenceManager 
        .getDefaultSharedPreferences(context); 

      Intent qteDay = new Intent(MainActivity.this, 
        QuoteActivity.class); 
      qteDay.putExtra("id", 
        preferences.getInt("id", IntialQteOfDayId)); 
      qteDay.putExtra("mode", "today"); 
      startActivity(today); 
     } 
    }); 

    btn_rateus.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      AlertDialog.Builder builder = new AlertDialog.Builder(
        MainActivity.this); 
      builder.setMessage(getResources().getString(
        R.string.ratethisapp_msg)); 
      builder.setTitle(getResources().getString(
        R.string.ratethisapp_title)); 
      builder.setPositiveButton(
        getResources().getString(R.string.rate_it), 
        new DialogInterface.OnClickListener() { 

         @Override 
         public void onClick(DialogInterface dialog, 
              int which) { 
          // TODO Auto-generated method stub 
          Intent fire = new Intent(
            Intent.ACTION_VIEW, 
            Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName()));   //dz.amine.thequotesgarden")); 
          startActivity(fire); 

         } 
        }); 

      builder.setNegativeButton(
        getResources().getString(R.string.cancel), 
        new DialogInterface.OnClickListener() { 

         @Override 
         public void onClick(DialogInterface dialog, 
              int which) { 
          // TODO Auto-generated method stub 
          dialog.dismiss(); 

         } 
        }); 
      dialog = builder.create(); 
      dialog.show(); 
     } 
    }); 




} 
void startTheThingWithData(){ 
    //Here data has value 
    Log.e(data, data); 
} 
/** 
* Async task class to get json by making HTTP call 
*/ 
private class GetAd extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // Showing progress dialog 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage("Please wait..."); 
     pDialog.setCancelable(false); 
     pDialog.show(); 

    } 

    @Override 
    protected Void doInBackground(Void... arg0) { 
     HttpHandler sh = new HttpHandler(); 

     // Making a request to url and getting response 
     String jsonStr = sh.makeServiceCall(url); 



     if (jsonStr != null) { 
      try { 
       JSONObject jsonObj = new JSONObject(jsonStr); 
       JSONObject dataa = jsonObj.getJSONObject("main1"); 
       String ad = dataa.getString("bnl"); 
       data = ad; 
       Log.e(TAG, "Response from url: " + ad); 


      } catch (final JSONException e) { 
       Log.e(TAG, "Json parsing error: " + e.getMessage()); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(getApplicationContext(), 
           "Json parsing error: " + e.getMessage(), 
           Toast.LENGTH_LONG) 
           .show(); 
        } 
       }); 

      } 
     } else { 
      Log.e(TAG, "Couldn't get json from server."); 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        Toast.makeText(getApplicationContext(), 
          "Couldn't get json from server. Check LogCat for possible errors!", 
          Toast.LENGTH_LONG) 
          .show(); 
       } 
      }); 

     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 
     // Dismiss the progress dialog 
     if (pDialog.isShowing()) 
      pDialog.dismiss(); 
     startTheThingWithData(); 
    }} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.menu_settings) { 
     Intent i = new Intent(this, UserSettingActivity.class); 
     startActivityForResult(i, RESULT_SETTINGS); 
    } 

    return super.onOptionsItemSelected(item); 
} 

这是它显示日志

E/MainActivity: Response from url: { 

      "main1": { 

      "bnl":"code" 
      } 
} 
+1

称它可能代替转向JSON为一个字符串即可只需将它作为JSON对象,然后使用内置方法来查找所需的键/值。 – csmckelvey

+0

可以请您给我的例子代码,即时通讯在JSON –

+0

点点新手我敢肯定,如果你对谷歌“Android中JSON对象,你会发现许多代码示例。 – csmckelvey

回答

1

要打印的jsonStr,而你想要的内容是数据。

AyncTasks异步运行,这意味着代码运行paralalel:检查这个简单的示例更好undestanding。

String b = "s"; 
void onCreate(Bundle b) { 
    afterAsyncHere(); 
    new Task().execute(); 
    afterAsyncHere(); 
} 

void afterAsyncHere() { 
    Log.e("onCreate", b); 
} 

class Task extends AsyncTask { 
    Object doInBackground(Object ... args) { 
     b ="value b"; 
     try { Thread.sleep(1000); }catch(Exception e) {} 
    } 
    void onPostExecute(Object r) { 
     afterAsyncHere(); 
    } 
} 
} 

上面的代码将调用afterAsyncHere()三次,两次在的onCreate和一个在onPostExecute。打印的结果将是: “S”从的onCreate “S”从的onCreate “值b”从onPostExecute

注意,在onPostExecute你的任务是总结和“b”的值进行了更新。 在第二次调用中(刚开始任务后),值仍然是“s”。

String ad = dataa.getString("bnl"); 
    data = ad; 
    Log.e(TAG, "Response.data from url: " + data); 

那会工作的实际代码是:

public class MainActivity extends ActionBarActivity { 

DataBaseHandler db; 
private AlertDialog dialog; 
public static final int IntialQteOfDayId = 8; 

final Context context = this; 
SharedPreferences preferences; 
private static final int RESULT_SETTINGS = 1; 
// This string will hold the results 
String data = ""; 
private String TAG = MainActivity.class.getSimpleName(); 

private ProgressDialog pDialog; 
// URL to get contacts JSON 
private static String url = "https://yourdomain.com/test.json"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
     getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 
      getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark)); 
} 
    new GetAd().execute(); 

    } 

void startTheThingWithData(){ 
    mNativeExpressAdView.setAdUnitId(data); 
    //Here data has value 
    Log.e(data, data); 
} 
/** 
* Async task class to get json by making HTTP call 
*/ 
private class GetAd extends AsyncTask<Void, Void, Void> { 

    @Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    // Showing progress dialog 
    pDialog = new ProgressDialog(MainActivity.this); 
    pDialog.setMessage("Please wait..."); 
    pDialog.setCancelable(false); 
    pDialog.show(); 

} 

@Override 
protected Void doInBackground(Void... arg0) { 
    HttpHandler sh = new HttpHandler(); 

    // Making a request to url and getting response 
    String jsonStr = sh.makeServiceCall(url); 

    Log.e(TAG, "Response from url: " + jsonStr); 

    if (jsonStr != null) { 
     try { 
      JSONObject jsonObj = new JSONObject(jsonStr); 
      JSONObject dataa = jsonObj.getJSONObject("main1"); 
       String ad = dataa.getString("bnl"); 
      data = ad; 



     } catch (final JSONException e) { 
      Log.e(TAG, "Json parsing error: " + e.getMessage()); 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        Toast.makeText(getApplicationContext(), 
          "Json parsing error: " + e.getMessage(), 
          Toast.LENGTH_LONG) 
          .show(); 
       } 
      }); 

     } 
    } else { 
     Log.e(TAG, "Couldn't get json from server."); 
     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       Toast.makeText(getApplicationContext(), 
         "Couldn't get json from server. Check LogCat for possible errors!", 
         Toast.LENGTH_LONG) 
         .show(); 
      } 
     }); 

    } 

    return null; 
} 

@Override 
protected void onPostExecute(Void result) { 
    super.onPostExecute(result); 
    // Dismiss the progress dialog 
    if (pDialog.isShowing()) 
     pDialog.dismiss(); 
    startTheThingWithData(); 
}} 

注意我加的活动的回调方法,并从onPostExecute

+0

是,我使用日志只是为了看看IM从代码中获得什么即时试图做的是存储'“BNL”'在宣布为空字符串'字符串数据=“”的价值;' –

+0

检查我的答案,你printlning的jsonStr不是数据变量,你的变量已经是正确的 –

+0

是的,但是当我执行的代码字符串数据=“”;不存储字符串广告的价值,你认为它应该存储在doInBackground –