2017-10-05 99 views
1

我試圖從JSON中使用Retrofit獲取單個值,我跟着一個教程,但我得到一個錯誤,指出「從回調派生的類匿名類必須聲明....」。 即時消息特別試圖實現的是回聲一個空字符串中的單個json屬性值,如String Axe = "";,我用來自服務器的json文件中的特定值填充它。這是我的嘗試。從響應中獲取單個JSON值Retrofit

JSON格式

"axe1": {"test1"} 

的ApiInterface

import com.google.gson.JsonObject; 

import retrofit2.Call; 
import retrofit2.http.GET; 

public interface ApiInterface { 
@GET("test.json") 
Call<JsonObject> readJsonFromFileUri(); 
} 

在MainActivity

import android.graphics.Typeface; 
import android.os.Build; 
import android.support.v7.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.net.Uri; 
import android.preference.PreferenceManager; 
import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.WindowManager; 
import android.widget.ImageView; 
import android.widget.TextView; 


import com.android.volley.Response; 

import com.google.gson.Gson; 
import com.google.gson.JsonObject; 


import retrofit2.Call; 
import retrofit2.Callback; 
import retrofit2.Retrofit; 
import retrofit2.converter.gson.GsonConverterFactory; 


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; 
// URL of object to be parsed 
// This string will hold the results 
String data = ""; 
class Myads{ 
    String bnr; 
    String intt; 
} 
@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)); 
    } 

    Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl("https://yourdomain.com/s/ ") 
      .addConverterFactory(GsonConverterFactory.create()) 
      .build(); 

    ApiInterface apiInterface = retrofit.create(ApiInterface.class); 

    Call<JsonObject> jsonCall = apiInterface.readJsonFromFileUri(); 
    jsonCall.enqueue(new Callback<JsonObject>() { 
     @Override 
     public void onResponse(Call<JsonObject> call, Response<JsonObject> response) { 
      JsonObject json = new JsonObject(body().toString()); 
      Gson gson = new Gson(); 
      Myads ad = gson.fromJson(jsonString, Myads.class); 
      Log.i(LOG_TAG, String.valueOf(ad.bnr)); 
     } 

         @Override 
         public void onFailure(Call<JsonObject> call, Throwable t) { 
          Log.e(LOG_TAG, t.toString()); 
         } 

        }); 


    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", "allQuotes"); 
      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", "isFavorite"); 
      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", "qteday"); 
      startActivity(qteDay); 
     } 
    }); 

    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(); 
     } 
    }); 




} 


@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); 
} 
} 

所以,我婉t內是test1的被解析並投入到空字符串的Json AXE1的價值

+1

發佈崩潰的唯一部分刁難。我們能完全崩潰嗎? – WoogieNoogie

回答

2

您正在使用錯誤的導入:

import com.android.volley.Response; 

import retrofit2.Response; 
+0

我跟着這個問題的答案https://stackoverflow.com/questions/37221570/get-single-json-property-value-from-response-json-using-retrofit-2 –

+0

@ Sebstian.RI認爲你搞砸了進口。發佈它們。 –

+0

@ Sebstian.R你有沒有使用'import retrofit2.Response;'? –

0

首先,你的JSON替換它格式無效,應該是{「axe1」:「test1」}。

要保存它,你可以這樣做:

JSONObject json = new JSONObject(response.body().toString()); 
Log.i(LOG_TAG, json.getString("axe1")); 
+0

我認爲格式很好,我跟着這個問題的答案https://stackoverflow.com/questions/37221570/get-single-json-property-value-from-response-json-using-retrofit-2 –

+0

如果你仔細看看你提到的帖子的截圖,你可以看到{}之間沒有唯一的屬性。你必須把{key:attr}而不是key:{attr} – ArteFact

+0

opp,是的,這是正確的,但我得到另一個錯誤是,當我複製從該答案的代碼,看看這張照片:https:// prnt.sc/gtnf53 –